Reputation: 81
I am building todoList that when I check the box, the component is disappeared. I tried to identify each checkbox with index!
So, I make state:checkedItem
, which have a "false or true" state in each checkbox. But, it doesn't render right away.
Here is my code sandbox : https://codesandbox.io/s/old-voice-6xyovb?file=/src/App.js
import "./styles.css";
import React from "react";
const todos = [
{ id: 0, value: "Wash the dishes" },
{ id: 1, value: "have lunch" },
{ id: 2, value: "listen to music" },
{ id: 3, value: "running" },
{ id: 4, value: "work out" }
];
export default function App() {
const [items, setItems] = React.useState(todos);
const [checkedItems, setCheckedItems] = React.useState(
new Array(todos.length).fill(false)
);
const checkHandler = ({ target }, idx) => {
checkedItems[idx] = !checkedItems[idx];
setCheckedItems(checkedItems);
//I want to identify idx ..
};
return (
<div className="App">
{items.map((todo, idx) => (
<div key={idx}>
<span>{todo.value}</span>
<input
type="checkbox"
checked={checkedItems[idx]}
onChange={(e) => checkHandler(e, idx)}
></input>
</div>
))}
</div>
);
}
Upvotes: 0
Views: 57
Reputation: 593
Here, I've updated your sandbox with notes and fixes.
https://codesandbox.io/s/objective-ioana-b04r8f?file=/src/App.js
Upvotes: 1
Reputation: 99523
The issue is that you call setCheckedItems
but you give it the exact same array, so this is not considered a change.
To fix this, make sure you give it a new array:
setCheckedItems([...checkedItems]);
Upvotes: 1