mardi 22 mars 2022

FluentUI/React - Get key of dynamic checkbox list onChange

Using React 17 with Fluent UI, I am trying to create a dynamic list of checkboxes. I have created the list of checkboxes, but I am struggling to get the key of each checkbox when they are selected, to update the state that is meant to be an array containing the keys of all the selected checkboxes.

I am open to suggestions that use a different property other than the key of the checkbox to store the values, but I am limited to using Fluent UI.

Here is the code I have used to generate the list of checkboxes (This is working). profiles is an array of objects that was created, the only properties that are used in this code is name and token which are both strings:

const getProfileCheckboxes = () => {
    var profiles = ProjectManager.getProfileList();
    const checkboxes = profiles.map(profile => 
        <Checkbox
            label={profile.name}
            defaultChecked={true}
            onChange={onChangeProfileCheckbox}
            key={profile.token}
        />
    );
    return checkboxes;
}

Below is where I am having issues, I have tried quite a few things for this function including all the answers to the related questions that I have found on Stack Overflow, but I have had no luck.

selectedProfiles defaults to an array containing all the profile tokens.

const onChangeProfileCheckbox = (ev: any) => {
    const value = "key of profile"; // Placeholder
    const checked = false; // Placeholder
    if (checked) {
        selectedProfiles.push(value);
    } else {
        setSelectedProfiles(prev => prev.filter(x => x !== value));
    }
}

Does anybody know how I can get the key and checked values in the onChange() function?

The checked values is less important since I can just check if the key is already contained in the state array, but I think it would be cleaner if I could get the value directly.

Thanks for the help!




Aucun commentaire:

Enregistrer un commentaire