I am trying to change the state of a checkbox when I have two, but all checkboxes are being checked at the same time, I tried different solutions for 5 days and still nothing … I’m quite new to react so I’m lost.
import React, { ChangeEvent, useCallback, useState } from 'react';
import ReactDOM from 'react-dom';
import { Checkbox, Pane } from 'evergreen-ui';
function ControlledCheckboxExample() {
const [checkedItems, setCheckedItems] = React.useState(false)
const handleButtonClick = (e) => {
console.log(!checkedItems, e);
setCheckedItems(!checkedItems);
};
return (
<Pane>
<Checkbox
label="Controlled usage"
name="afaf"
key={1}
checked={checkedItems}
onChange={handleButtonClick.bind(name, 1)}
/>
<Checkbox
label="Controlled usage"
name="afatrf"
key={2}
checked={checkedItems}
onChange={handleButtonClick.bind(name, 2)}
/>
</Pane>
)
}
ReactDOM.render(
<ControlledCheckboxExample />,
document.getElementById("root")
)
This is my code, is there any solution you can propose?
>Solution :
Issue
The code is using and updating a single state for all checkbox inputs.
Solution
Convert the checkedItems to an object of booleans and use the onChange event object and the input name to toggle a specific input.
Example:
function ControlledCheckboxExample() {
const [checkedItems, setCheckedItems] = React.useState({});
const handleButtonClick = (e) => {
const { name } = e.target;
setCheckedItems(checkedItems => ({
...checkedItems,
[name]: !checkedItems[name]
}));
};
return (
<Pane>
<Checkbox
label="Controlled usage"
name="afaf"
key={1}
checked={checkedItems["afaf"]}
onChange={handleButtonClick}
/>
<Checkbox
label="Controlled usage"
name="afatrf"
key={2}
checked={checkedItems["afatrf"]}
onChange={handleButtonClick}
/>
</Pane>
);
}