Home > Mobile >  How to change checkbox state for one element instead of all
How to change checkbox state for one element instead of all

Time:09-18

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?

CodePudding user response:

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

Edit how-to-change-checkbox-state-for-one-element-instead-of-all

CodePudding user response:

You are using same state variable for both checkboxes and of course if you click on one the second will be set too. Create another state variable for another checkbox or use an array like so

const [state, setState] = React.useState(new Array({length of how much boxes you have}).fill(false);

and then update state

const handleOnChange = (position) => {
const updatedCheckedState = checkedState.map((item, index) =>
  index === position ? !item : item
);

setCheckedState(updatedCheckedState);

}

  • Related