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.
Here is a Code Sandbox with a minimal reproducible example: https://codesandbox.io/s/heuristic-parm-1l3yyc?file=/src/App.tsx
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!
CodePudding user response:
You can get checked
value directly from event that we have from onChange
The key
property is used by React under the hood, and is not exposed to you. You'll want to use a custom property and pass that data in or as in your case, pass it directly into onClick function
here is how Checkbox should look:
<Checkbox
label={profile.name}
defaultChecked={true}
onChange={(ev) => onChangeProfileCheckbox(ev, profile.token)}
key={profile.token}
/>
And here how your onChange function should look:
const onChangeProfileCheckbox = (ev: ChangeEvent<HTMLInputElement>, token: string) => {
const value = token;
const checked = ev.target.checked;
if (checked) {
selectedProfiles.push(value);
} else {
setSelectedProfiles(prev => prev.filter(x => x !== value));
}
};
here is the link to codesandbox with the result