Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle checked in input type='checkbox' in React?

I have a group of checkboxes, some of them are pre-checked and some will be updated from the user. problem is the checkboxes render fine in initial render but they don't change on click. The value of 'checked' gets updated on change (onChange)

<input
   type = 'checkbox'
   style = {{margin : '0'}}
   checked = {this.state[elem]}
   value = {elem}
   onChange = {this.checked}
 /> {elem}

and in the checked method

checked = e => {
    this.setState({
        [e.target.value] : !this.state[e.target.value]
    })
}
like image 803
shahriar hasan Avatar asked Sep 15 '25 23:09

shahriar hasan


1 Answers

You haven't shared with us how you are generating these inputs, but the primary issue has to do with using a single source of truth for all your inputs. You want to give each input, particularly the object that corresponds to that input, their own checked-state.

Considering the following example with working codesandbox: https://codesandbox.io/s/relaxed-feynman-1thb8

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const arr = [
  { val: "Cat", checked: false },
  { val: "Dog", checked: true },
  { val: "Turtle", checked: false }
];

class App extends React.Component {
  state = {
    arr: arr
  };

  handleCheck = e => {
    const arrCopy = [...this.state.arr];
    const itemToUpdate = arrCopy.find(item => item.val === e.target.value);

    itemToUpdate.checked = !itemToUpdate.checked;

    this.setState({
      arr: arrCopy
    });
  };

  createInputs = () => {
    const { arr } = this.state;

    return arr.map(elem => {
      return (
        <div>
          <input
            type="checkbox"
            style={{ margin: "0" }}
            checked={elem.checked}
            value={elem.val}
            onChange={this.handleCheck}
          />
          {elem.val}
        </div>
      );
    });
  };

  render() {
    return <div>{this.createInputs()}</div>;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

In the above code, we organize your state-data as in array of objects, making it easier for you to render the mark-up AND keep track of the checked state of each input. Then in the handleCheck function, we identify the checked item, find its corresponding object in the array and toggle the checked state of that item.

like image 93
Chris Ngo Avatar answered Sep 18 '25 13:09

Chris Ngo