I am trying to implement checkbox in react but I am facing a issue while checking and uncheck of checkbox.
I tried to implement onchange handler .
onChange={() => {
// first approch
// i.checked = !i.checked;
// setObj({ ...i});
// second approach
setObj({ ...i, checked: !i.checked });
setTimeout(ab, 2000);
}}
so I used two approach
In First approach i changed the toggle the checked property and then create new reference which is working fine
i.checked = !i.checked;
setObj({ ...i});
In second approach I created a new object or reference with toggle of checked property but this is not working why
{ ...i, checked: !i.checked }
why my first and second approach is different ?
here is my code
https://codesandbox.io/s/lucid-fire-cxp9c?file=/src/child.js:362-666
import React from "react";
export default function Child({ data, ab }) {
const [obj, setObj] = React.useState(null);
return (
<>
{data &&
data.map((i, idx) => {
return (
<ul key={idx}>
<li>
<input
type="checkbox"
checked={i.checked}
onChange={() => {
// first approch
// i.checked = !i.checked;
// setObj({ ...i});
// second approach
setObj({ ...i, checked: !i.checked });
setTimeout(ab, 2000);
}}
/>
{i.label}
</li>
{i.childrens && i.childrens.length > 0 ? (
<Child data={i.childrens} ab={ab} />
) : null}
</ul>
);
})}
</>
);
}
any suggestion ...!!?