handleOnChan">
I ran several checkboxes in several checkbox groups. I can't figure out how to uncheck (thereby changing the state) a specific checkbox. For some reason I can't access e.target.checked
.
handleOnChange(e)} />
and my functions
const handleOnChange = (e) => { const check = e.target.checked; setChecked(!check); };
I made a working example of the component in this sandbox.
Here's how I did it:https://codesandbox.io/s/elastic-pateu-flwqvp?file=/components/Selectors.js
I abstracted the selection logic into a
useSelection()
custom hook, which means the current selection can be found instore[key].selected
, wherekey
can be any key ofselectors
.items
,selected
,setSelected
andsectionLabel
are stored in eachuseSelection()
call Instore[key]
, and passed to a
component.The relevant part is the
handleCheck
function within this component, which sets the new selection based on the previously selected value: if the currentitem
is contained within the previouslyselected
value, remove it. Otherwise, add it.More detailed explanation (why)
Looking closely at your code, it seems like you are confused about how the checkbox component works in React.
Thechecked
attribute of
input
is controlled by aboolean
state. Generic example:On each render, the
checked
value ofis set based on the current value of the
checked
state. When the enteredchecked
changes (during user interaction), the status is not automatically updated. But theonChange
event is fired and we use it to update the state to the negative value of the state's previous value.When dealing with the
In order for this to work, we need to update the value of the
component,wecannotuse a single boolean value to controlallcheckboxes, we need to set a boolean value for each checkboxbeing rendered. So we create aselectedarray and set the
checkedvalue of each
to
selected.includes(item) The value of(returns a
boolean).
selected
Hope this solves some problems.array in every
onChangeevent. We check if
itemis contained in the previous version of
selected. If present, filter it out. If it doesn't exist, add it:
You need to create specific handleOnChange function for each group. I have created a similar function for the Genre checkbox group and you can create it for other groups in the same way.
This is the processing function.
Pass this function to CustomCheckboxGroup as the handleOnChange attribute as shown below.
For testing, comment out your handleOnChange function.
See the complete working solution in the sandbox -Complete code