how to Uncheck Checkbox.Group in Antd React.js

Mandoxsy picture Mandoxsy · Jun 21, 2019 · Viewed 11.1k times · Source

I have the following Code using https://ant.design/components/checkbox/, and Trying to uncheck when a checkbox has been checked. I don't want to check all if button is click, just Uncheck all or the one checkbox selected.

Any help will be appreciate!

Answer

Dhaval Jardosh picture Dhaval Jardosh · Jun 21, 2019

Working Link

The toggle on the checkbox wasn't working due to Checkbox.Group, you can simply use Checkbox


Regarding Checkbox State:

You can't have a single state for all the checkboxes, so you will need to have an array of bool which will serve as the state for each checkbox item.

In the example, I have initialized checkbox state on componentDidMount and it creates an array ([false,false,false,...]) and the exact same thing is used for resetting on Uncheck. (Possibility of refactoring in my code)

User assigned state will decide whether to check the checkbox or not.

import React from "react";
import ReactDOM from "react-dom";
import { Button, Checkbox } from "antd";
import "antd/dist/antd.css";
import "./index.css";

let data = [3423, 3231, 334234, 55345, 65446, 45237];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checkboxArray: []
    };
    // this.onChange = this.onChange.bind(this);
  }

  componentDidMount() {
    let createEmptyArray = new Array(data.length).fill(false);
    this.setState({ checkboxArray: createEmptyArray });
  }

  onChange(e) {
    console.log(e.target);
  }

  onChangeBox = (e, i) => {
    let checkBoxCurrentState = this.state.checkboxArray;
    checkBoxCurrentState[i] = !checkBoxCurrentState[i];
    this.setState({
      checkboxArray: checkBoxCurrentState
    });
  };

  unChecked = e => {
    let resetArray = new Array(data.length).fill(false);
    this.setState({
      checkboxArray: resetArray
    });
  };

  render() {
    const { data } = this.props;
    return (
      <div>
        <Button type="primary" size="small" onClick={this.unChecked}>
          Uncheck
        </Button>

        <div>
          <div className="filter-subhead">Track</div>
          {data.map((i, index) => (
            <div className="filter-item">
              <Checkbox
                checked={this.state.checkboxArray[index] ? true : false}
                onChange={e => this.onChangeBox(e, index)}
                value={index}
              >
                {JSON.stringify(this.state.checkboxArray[index])}
              </Checkbox>
            </div>
          ))}
        </div>
        {JSON.stringify(this.state.checkboxArray)}
      </div>
    );
  }
}

ReactDOM.render(<App data={data} />, document.getElementById("root"));

Simple copy and paste the above code and add props where required.

And if you want to user Checkbox.Group, will need to update the onChange method of CheckBox.Group

let data = ['Apple', 'Pancakes', 'Butter', 'Tea', 'Coffee'];
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checkboxArray: []
    };
    // this.onChange = this.onChange.bind(this);
  }

  componentDidMount() {
    let createEmptyArray = new Array(this.props.data.length).fill(false);
    this.setState({ checkboxArray: createEmptyArray });
  }

  onChangeBox = (e, i) => {
    let checkBoxCurrentState = this.state.checkboxArray;
    checkBoxCurrentState[i] = !checkBoxCurrentState[i];
    this.setState({
      checkboxArray: checkBoxCurrentState
    });
  };

  unChecked = () => {
    let resetArray = new Array(data.length).fill(false);
    this.setState({
      checkboxArray: resetArray
    });
  };

  render() {
    const { data } = this.props;
    return (
      <div>
        <button onClick={this.unChecked}>Clear All</button>
        {this.props.data.map((single, index) => (
          <div>
            <input
              type="checkbox"
              id={index}
              name="scales"
              checked={this.state.checkboxArray[index]}
              onChange={e => this.onChangeBox(e, index)}
            />
            <label for={index}>{single}</label>
          </div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<App data={data} />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>