trying to store the value of checked boxes in and array. but im only getting the value of the recenlty checked one rather than storing all the checked boxes in the array.
function FilterButton() {
const [keyword, setKeyword] = useState([])
const onChange = (e) => {
setKeyword(e.target.value)
if (e.target.checked) {
setKeyword([e.target.value])
} else {
setKeyword('')
}
}
console.log(keyword)
return (
<input type="checkbox" value='1' onChange={onChange} />
<input type="checkbox" value='2' onChange={onChange} />
<input type="checkbox" value='3' onChange={onChange} />
<input type="checkbox" value='4' onChange={onChange} />
<input type="checkbox" value='5' onChange={onChange} />
<input type="checkbox" value='6' onChange={onChange} />
)
}
console.log(keyword) output when chekcing input 1,2 and 3:
`['1']`
`['2']`
`['3']`
desired output:
['1,2,3']
CodePudding user response:
You are overwriting the value on each checkbox change. Instead, create a new array:
const onChange = (e) => {
if (e.target.checked) {
setKeyword((v) => [...v, e.target.value])
} else {
setKeyword((v) => v.filter((x) => x !== e.target.value))
}
};
When passing a function into the setter returned from setState
, it will be called with the current value of the state at the time, allowing you to make accurate changes.
When the target is checked, you add the value to the array by spreading the existing values into it and adding the new one.
When the target is not checked, you filter it out of the array.
CodePudding user response:
const onChange = (e) => {
const value = e.target.value;
if (e.target.checked) {
setKeyword(keywords=> [...keywords, value ]);
} else {
setKeyword(keyword.filter(x=>x!=))
}
}