I'm trying to update checked property in list of todos array whenever an item is checked.
How do I update a specific item at that particular index.
For example,
[{name: 'todo1', checked: false},{name: 'todo2', checked: false}]
When I checked todo2, the updated array should be
[{name: 'todo1', checked: false},{name: 'todo2', checked: true}]
Code
const [todos, setTodos] = useState([]);
const [checked, setChecked] = useState(false);
const handleChange = (event, index) => {
console.log("index", index);
setChecked(event.target.checked);
};
console.log(todos);
return (
<>
{todos.map(
(item, index) =>
item.name && (
<div key={index}>
<Checkbox onChange={(e) => handleChange(e, index)} />
{item.name}
</div>
)
)}
<Formik
initialValues={{
todo: ""
}}
onSubmit={(values, { resetForm }) => {
setTodos([...todos, { name: values.todo, checked: checked }]);
resetForm({ values: "" });
}}
>
<Form>
<label htmlFor="todo"></label>
<Field id="todo" name="todo" placeholder="item" />
<button type="submit">Submit</button>
</Form>
</Formik>
</>
);
}
I created a working example using CodeSandbox. Could anyone please help?
