'click twice on checkbox to update state
I am mapping through this array
array=[
{'id': 1, 'isActive': true, 'name': apple},
{'id': 2, 'isActive': false, 'name': orange},
{'id': 3, 'isActive': false, 'name': forest}
]
I have an input that looks like this after the map of array
<input
id={item.id}
type="checkbox"
onClick={() => handleActive(item)}
checked={item.isActiveMarket}
/>
I want to change isActive inside the item when i click on the checkbox to activate or desactivate, but the array should stay full without deleting any element
For the function this is what I got
const handleActive = (item) => {
item.isActive = !item.isActive;
};
it works but only when I double click on it
Solution 1:[1]
Try to use onChange instead of onClick
Solution 2:[2]
Use the below code:
<input
id={item.id}
type="checkbox"
onChange={() => handleActive(item)}
checked={item.isActiveMarket}
/>
Solution 3:[3]
const initialState = [
{'id': 1, 'isActive': true, 'name': apple},
{'id': 2, 'isActive': false, 'name': orange},
{'id': 3, 'isActive': false, 'name': forest}
];
const [items, setItems] = useState(initialState);
const onActiveToggle = (id) => {
const item = items.find(item => item.id === id);
setItems(prev => prev.splice(prev.indexOf(item), 1, {...item, isActive: !item.isActive}));
}
...
...
<>
{items.map((item, index) => (
<input
key={item.id}
id={item.id}
type="checkbox"
onChange={() => handleActive(item.id)}
checked={item.isActive}
/>
))}
</>
...
...
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 | Voidy |
| Solution 2 | apps |
| Solution 3 | Mykola MASTEMA |
