'Unable to check and uncheck the dynamically rendered checkboxes in react
I am iterating over the permissions and make checkbox checked if permission included in a predefined values(i.e val) and make checkbox unchecked otherwise, which it did well, but when I click the rendered checkboxes to check or to uncheck it do nothing.
I can't check or uncheck after I rendered my checkboxes. I need your help , thanks.
Solution 1:[1]
Your role.permissions is never getting updated, so the checkbox checked attribute stays as its initial value. Are you using controlled components? If so, you can add an onChange event handler to your input to update your role.permissions.
Solution 2:[2]
Firstly, the ternary operation in checked={role?.permissions?.includes(val[i]) ? true : false} is redundant and can be simplified to just checked={role?.permissions?.includes(val[i])}, since the value of that property will be either true or false anyway.
Secondly, by setting value= to true or false, you are freezing the checkbox to that value. You can omit that setting, as the value attribute will be submitted according to the checked or unchecked value. Also, typically you assign value=checked or value=unchecked, not true and false.
Solution 3:[3]
use map function and useState to control your checkbox values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Dexter |
| Solution 3 | mahmoud2020 |

