lundi 16 mars 2020

On closing the tag the checkbox element should be unchecked in the checkbox group

I have a checkbox and a tag component. On checking each element a tag of that element is displayed below which is achieved by the below code. But I want to map each tag with the respective checkbox element. When I remove the tag of an element, the corresponding element should be unchecked from the checkbox. Now when I remove the tag the checkbox is still checked. Link to my code https://codesandbox.io/s/quizzical-borg-77nlv

import React, { Component } from "react";
import { Checkbox, Tag } from "antd";
class Filters extends Component {
  state = {
    tags: []
  };
  onCheck = e => {
    let tags = [...this.state.tags];

    tags = tags.filter(v => v !== e.target.value);

    e.target.checked && tags.push(e.target.value);

    this.setState({ tags });
  };

  onCloseTag = (e, i) => {
    e.preventDefault();
    this.setState({
      tags: this.state.tags.filter((_, index) => index !== i)
    });
  };

  render() {
    const { tags } = this.state;
    return (
      <React.Fragment>
        <div>
          CHECKBOX 1
          <Checkbox.Group name="checkbox_1" style=>
            <Checkbox
              onChange={this.onCheck}
              checked={tags.includes("a")}
              value="a"
            >
              A
            </Checkbox>
            <Checkbox
              onChange={this.onCheck}
              checked={tags.includes("b")}
              value="b"
            >
              B
            </Checkbox>
          </Checkbox.Group>
        </div>
        <div>
          CHECKBOX 2
          <Checkbox.Group
            name="checkbox_2"
            onChange={this.onCheck1}
            style=
          >
            <Checkbox
              onChange={this.onCheck}
              checked={tags.includes("2a")}
              value="2a"
            >
              2A
            </Checkbox>
            <Checkbox
              onChange={this.onCheck}
              checked={tags.includes("2b")}
              value="2b"
            >
              2B
            </Checkbox>
          </Checkbox.Group>
        </div>
        <div style=>
          {tags.map((tag, i) => (
            <Tag
              className="quick-filter-tag-main"
              key={i}
              closable
              onClose={e => this.onCloseTag(e, i)}
              color="#f50"
            >
              {tag}
            </Tag>
          ))}
        </div>
      </React.Fragment>
    );
  }
}
export default Filters;




Aucun commentaire:

Enregistrer un commentaire