I have this piece of code that I would like to use
const traits = [{title:"hello", effect:"world"},{title:"foo", effect:"bar"}];
const [ traitsArray, settraitsArray ] = useState([]);
to be rendered as Checkbox element
{traits.map((items)=>{
return <FormControlLabel
label={items.title}
key={items.title}
control={<Checkbox data-value={items.title} checked={false} onChange={ e => {
if(traitsArray.includes(e.target.getAttribute('data-value'))){
settraitsArray(prevState => prevState.filter(items => items !== e.target.getAttribute('data-value')))
}
else{
settraitsArray(prevState => prevState.concat(items))
}
} }/>}/>})}
On checked item, I would like to check if any of the similar value exist in traitsArray
, if true, delete the element from the array, and if false, add the element to the array.
But every single time I checked the item, it just keep on concatenating the array. Did I miss something, or did I code it the wrong way?
In your onChange
function you are checking to see if your array includes a string but then if it doesn't you're adding an object. Your function should look like this:
(e) => {
if(traitsArray.some(({title}) => title === items.title)){
settraitsArray(prevState => prevState.filter(item => item.title !== items.title))
} else {
settraitsArray(prevState => prevState.concat(items))
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments