I'm trying to build a form where users will have to check mapped checkboxes, but every time I click on a checkbox nothing happens. The idea would be that every times user checks the box its value is added to an array. But when I log e.target.checked
I just see true
every times I click on the checkbox, never false. Also the checkbox doesn't check on a click. Does anyone know where this problem can come from?
This is my code:
const [arr, setArr] = useState([])
const handleCheck = e => {
if (e.target.checked) {
setArr([e.target.value, ...arr])
} else {
setArr(arr.filter(value => value !== e.target.value))
}
}
And JSX:
{results.map(person => (
<li key={uuid()}>
<input
type="checkbox"
id={`user-${person._id}`}
value={person._id}
onChange={handleCheck}
name="name"
/>
{person.fullName}
</li>
))}
Thanks for your help!
CodePudding user response:
You are generating random React keys each render cycle, so the uncontrolled inputs effectively reset each time. Use the person._id
as the React key so you've stable references identifying the list items and inputs.
{results.map((person) => (
<li key={person._id}>
<input
type="checkbox"
id={`user-${person._id}`}
value={person._id}
onChange={handleCheck}
name="name"
/>
{person.fullName}
</li>
))}