jeudi 19 mars 2020

How to select multiple checkbox for reactjs

I created initial state.

state :
      listofdata: [],
      role: [],
      notification: {},
      arr: [],
      permission: {},
      fruites: this.props.all_permissions

Method: I created this method for each checkbox, it will be give me. this kinds of data format.I can also removed unchecked value.

   {
        notification : {group:["can_view","can_create", "can_delete","can_update","can_upload","can_download"],
        topGroup:["can_view","can_create", "can_delete","can_update","can_upload","can_download"}
        }




    handleChange = (role, item) => {
        const { listofdata } = this.state;
        const newList = [...listofdata];

        const itemIndex = newList.findIndex(
          (index, i) => index.rolename === role && index.value === item.value
        );
        const notification = {};
        if (itemIndex > -1) {
          newList.splice(itemIndex, 1);
          this.removeItem(role, item.value);
        } else {
          newList.push({
            value: item.value,
            rolename: role
          });

          for (const { value, rolename } of newList) {
            if (!notification[rolename]) notification[rolename] = [];
            notification[rolename].push(value);
          }
          this.setState({
            notification
          });
        }

    this.setState({
      listofdata: newList
    });
  };
      removeItem = (obj, arr) => {
        let arrs = [...this.state.arr];
        arrs.push(arr);
        for (var key of Object.keys(this.state.notification)) {
          if (key === obj) {
            this.state.notification[key] = this.state.notification[key].filter(
              i => !arrs.includes(i)
            );
          }
        }
        this.setState({ notification: this.state.notification });
        return this.state.notification;
      };

      onSubmitHandler = () => {
        // console.log("state", this.state.notification);
      };

I need to get array of objects when user click on the group based role . I can not pass my accepted data. Here is my accepted data

 {

    notification : {group:["can_view","can_create", "can_delete","can_update","can_upload","can_download"],
    topGroup:["can_view","can_create", "can_delete","can_update","can_upload","can_download"}
    }


  handleAllChecked = (id, role, data) => event => {
    let fruites = this.state.fruites;
    fruites
      .filter(f => f.groupId === id)
      .forEach(fruite => {
        if (event.target.checked === true) {
          fruite.isChecked = event.target.checked;

          console.log(data);
        } else {
          fruite.isChecked = false;
        }
      });

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

This is method is going for select individual checkbox

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

render UI : I want to display list of checkbox inside each role . If I click on the role name,Forexample : Group , it will select group based all checkboxes. If I click on the topgroup , it will select topgroup based all checkbox. I can do this, but

The problem is that I need to pass array of object , I can not get my accepted data .My accepted data will be this format. However, user can remove by using unchecked.

{ notification : {group:["can_view","can_create", "can_delete","can_update","can_upload","can_download"], topGroup:["can_view","can_create", "can_delete","can_update","can_upload","can_download"} }

              {[{id:0,name:"group"},{id:1,name:"topGroup"].map((item, index) => (

   //Role Name:
      <input
                            type="checkbox"
                           onChange={this.handleAllChecked(
                              item.id,
                              item.name,
                              this.state.fruites
                            )}
                            value="checkedall"
                          />
                        <label>{item.name}</label>


                      {this.state.fruites
                        .filter(fruit => fruit.groupId === item.id)
                        .map((fruite, index) => (

                              <input
                                key={fruite.id}
                                onClick={() => this.handleChange(item.name, fruite)}
                                onChange={this.handleCheckChieldElement}
                                type="checkbox"
                                checked={fruite.isChecked}
                                value={`${item.id}-${fruite.id}`}
                              />{" "}

                        ))}

                ))}

        <button
                className="btn btn-primary btn-md waves-effect waves-light"
                onClick={this.onSubmitHandler}
              >
                Add user
              </button>

Here is my codesanbox , You can easily understand https://codesandbox.io/s/fragrant-http-v35lf




Aucun commentaire:

Enregistrer un commentaire