mercredi 18 mars 2020

how to select All checkbox based group in reactjs

I did initial state for select single checkbox .Here is my intial state

     this.state = {
          fruites: [
            { id: 1 , value: "banana", isChecked: false },
            { id: 2, value: "apple", isChecked: false },
            { id: 3,value: "mango", isChecked: false },
            { id: 4, value: "grap", isChecked: false }
          ]
        };
      }

Method: I just this for selected all checkbox

      handleAllChecked = id => event => {
        let fruites = this.state.fruites;
        fruites.forEach(fruite => {
          data.filter(item => 
              fruite.isChecked = event.target.checked;

          });
        });
        this.setState({ fruites: fruites });
      };

I just this method for individual checkbox .

      handleCheckChieldElement = event => {
        let fruites = this.state.fruites;
        fruites.forEach(fruite => {
          if (fruite.value === event.target.value)
            fruite.isChecked = event.target.checked;
        });
        this.setState({ fruites: fruites });
      };

Render:Here is my UI, I want to select All checkbox based on group . For example , I have got two group of value - such as Group , Topgroup. The problem is that , When I click on the group , it will select All checkbox including Topgroup and also I click banana , it will select all banana , I don't want to get all banana when click on one item. I don't to want to get topgroup checkbox when I select on the group.

            {[{ id: 1, name: "group" }, { id: 2, name: "topGropup" }].map(item => (
              <div>
                <input
                  type="checkbox"
                  onChange={this.handleAllChecked(item.id)}
                  value="checkedall"
                />{" "}
                {item.name}
                <ul>
                  {this.state.fruites.map((fruite, index) => {
                    return (
                      <CheckBox
                        key={index}
                        handleCheckChieldElement={this.handleCheckChieldElement}
                        {...fruite}
                      />
                    );
                  })}
                </ul>
              </div>
            ))}
          </div>

How can I resolve this problem . Here is my codesanbox : https://codesandbox.io/s/react-multi-select-checkbox-or6ko




Aucun commentaire:

Enregistrer un commentaire