Search code examples
reactjsantd

ant design clear all checkboxes


How to clear the checkboxes in the checbox.group?

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

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checkedList: [],
      checkAll: false
    };
  }

  groupChange = checkList => {
    this.state({
      checkList
    });
  };

  clearAll = e => {};

  render() {
    return (
      <div>
        <Checkbox onChange={this.clearAll}>Clear all</Checkbox>
        <Checkbox.Group
          value={this.state.checkList}
          onChange={this.groupChange}
        >
          <Checkbox value={1}>One</Checkbox>
          <Checkbox value={2}>Two</Checkbox>
        </Checkbox.Group>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("container"));

Solution

  • you have to pass options in checkbox group instead of <checkbox> as a child

    codesandbox: https://codesandbox.io/s/charming-shape-xjfxx?file=/index.js

    import React from "react";
    import ReactDOM from "react-dom";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Checkbox } from "antd";
    
    const options = [{ label: "One", value: 1 }, { label: "Two", value: 2 }];
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          checkedList: [],
          checkAll: false
        };
      }
    
      groupChange = checkedList => {
        this.setState({
          checkedList
        });
      };
    
      clearAll = e => {
        this.setState({ checkedList: e.target.checked ? [1, 2] : [] });
      };
    
      render() {
        return (
          <div>
            <Checkbox onChange={this.clearAll}>Clear all</Checkbox>
            <Checkbox.Group
              options={options}
              value={this.state.checkedList}
              onChange={this.groupChange}
            />
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("container"));