0

How I would create a functional component with exactly 4 checkboxes? I have created dynamically mapping an array and I set its value with:

const [checked, setChecked] = useState([false, false, false, false])

and then, with a function I change its state, something like:

const checkboxes = array.map( (el, index) => {

return <Checkbox

checked={checked[index]}

onChange={checkedHandler}/>

}

This is the handler:

const checkedHandler = (event, index) => {

setChecked(...)

//Well, here I don't know how change the particular value of the array...

}

Or I must create a useState for each Checkbox checked state? And how pass the state of this Checkbox to the father component if it was necessary?

enter image description here

Tabi
  • 109
  • 2
  • 6
  • 1
    Does this answer your question? [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) – Vencovsky Dec 18 '19 at 15:04

3 Answers3

2

You are invoking the checkedHandler wrong way. You have:

onChange={checkedHandler}

And you should have:

onChange={() => {checkedHandler(index)}}

In the handler itself you should copy your current array to prevent its mutation and change the value of the indexed one:

const checkedHandler = (index) => {
  const newChecked = [...checked];
  newChecked[index] = !checked[index]; // toogle the checkbox
  setChecked(newChecked);
}
Wojciech Dynus
  • 911
  • 5
  • 11
2

Assign id to each checkbox like id="1", id="2" and so on...

Then your checkedHandler() function be like:

checkedHandler(event) {
    const newChecked = [...checked]
    newChecked[parseint(event.target.id) - 1] = true
    setChecked(newChecked)
}
Akshit Mehra
  • 747
  • 5
  • 17
1

There is ALOT of ways you can do this, if you case is simple, you could just shallow copy the array and change only the index you want.

let newChecked = [...checked]
newChecked[index] = value
setChecked(newChecked)

But for more complex cases, please take a look at Correct modification of state arrays in ReactJS

Vencovsky
  • 28,550
  • 17
  • 109
  • 176