Alvin
Alvin

Reputation: 8509

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

Upvotes: 1

Views: 3941

Answers (2)

Oren A
Oren A

Reputation: 31

const [checkedList, setCheckedList] = useState([]);
 
<Checkbox onChange={()=> setCheckedList([])}>Clear all</Checkbox>
    <Checkbox.Group
      options={options}
      value={checkedList}
      onChange={(checkedValues) => setCheckedList(checkedValues)}
    />

Upvotes: 0

Nihal Saxena
Nihal Saxena

Reputation: 1006

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

Upvotes: 4

Related Questions