'Using checkboxes created with map method in react js
Hope you can help me here.
Lets say i have a list of items created using map method in react js.
Each list of items contains text and checkbox (checkbox from materual ui lib).
Now i have a problem with using checkboxes, as when i add controls to them (checked and onChange()) props - whenever i tick 1 box - all boxes are ticked. And vice versa.
However, the idea is that once I check 1 checkbox - it should cross out the text next to the that box (some kind todo list).
Please, give me some hits how can i do that? How to be able each checkbox.
<div className="lidiv">
{items.map((item: any, index: number) => (
<li
key={item.id}
style={{
background: index % 2 === 0 ? "lightgray" : "transparent",
padding: 3,
textDecoration: decor,
}}
>
{index + 1}
<Box> {item.description}</Box>
<Box>
<Checkbox
checked={checked}
onChange={(e) => handleTick(item.id, e)}
/>
<DeleteIcon
sx={{ color: red[500], mb: -1 }}
onClick={() => deleteItem(item.id)}
/>
</Box>
</li>
))}
</div>
Solution 1:[1]
You didn't post the important part of the code and from your comment it seems that you were handling every items in one state, you need to have state for each item.
const { useState } = React
const App = () => {
const [items, setItems] = useState([{
name: 'test 1',
checked: false
}, {
name: 'test 2',
checked: false
}, {
name: 'test 3',
checked: false
}]);
const handleCheckBox = (event, index) => {
const checked = event.target.checked;
setItems(items => {
return [
...items.slice(0, index),
{...items[index], checked},
...items.slice(index + 1),
]
})
}
return (
<div>
{
items.map((item, i) =>
<div key={i}>
<input type="checkbox" onChange={(e) => handleCheckBox(e, i)}/>
<span style={{ textDecoration: item.checked? 'line-through': 'none' }}>{item.name}</span>
</div>
)
}
</div>
)
}
ReactDOM.render(<App />,document.getElementById("root"))
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jefery Only |
