Home > database >  click twice on checkbox to update state
click twice on checkbox to update state

Time:05-19

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

CodePudding user response:

Try to use onChange instead of onClick

CodePudding user response:

Use the below code:

<input
    id={item.id}
    type="checkbox"
    onChange={() => handleActive(item)}
    checked={item.isActiveMarket}
/>

CodePudding user response:

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}
/>
  ))}
</>

...
...
  • Related