I want to make checkboxes controlled, handleChange does the job and toggles the completed property but react doesn't rerender the dom I suppose. How do I make it work?
import React from "react";
export default function App() {
const [items, setItems] = React.useState([
{ title: "Item 1", completed: false, id: 1 },
{ title: "Item 2", completed: false, id: 2 },
{ title: "Item 3", completed: false, id: 3 }
]);
function handleChange(index) {
const itemsRef = items;
itemsRef[index].completed = !itemsRef[index].completed;
setItems(itemsRef);
}
return (
<div id="app">
<ul>
{items.map((item, index) => (
<li key={item.id}>
<input
type="checkbox"
checked={item.completed}
onChange={() => handleChange(index)}
/>
<label>{item.title}</label>
</li>
))}
</ul>
</div>
);
}