I have an array that creates checkboxes, which works, but I also have another array which is constructed from a user array including the rights a user has. Now based on that second array, I want to have a checkbox shown checked if the user has that specific right.
Here is what I have:
return (
<>
{listOfRights.map((item, index) => {
const roleChecked = userRoles.map((role) => role.RoleId === item.id);
return <Form.Check
key={index}
inline
name="userRights"
isInvalid={!!errors.user_rights}
label={getRightsTitle(item.roleName)}
value={item.id}
onChange={handleChange}
id={`user_rights-${item.id}`}
checked={roleChecked}
/>
})}
</>
)
listOfRights has all the rights, which shows the correct amount of checkboxes with each right. userRoles shows an array of:
[{
id: 1,
RoleId: 1,
UserId: 1
}]
What now happens is that all the checkboxes are checked and not just the one having the right the user has.
What am I missing?
2
Answers
The answer here is in your one-liner. You are setting your checkbox to a falsy "null" value instead of setting it to
false
— A "null" value is still a value, so it will check the box.Instead you should be setting the checkbox to
false
, thenmapping
, using anif
, then set totrue
if the IDs match.Am I going to use a multiline so that it makes more sense:
That should solve your falsy value and your checkboxes being mistakenly checked.
userRoles.map( ... )
produces an array of boolean values, and you then feed that whole array of booleans intochecked={ ... }
.You most likely need to use
some()
, which produces a single boolean value: