mardi 30 août 2022

Checkbox trigger multiple select with React

I'm building a React application for my clients. Each Client, when log-in, can access different views for each his location office. So first I list all the office of the client, and for each its office, he cans select the views he wants to display.

My Problem :

Let say I have office 1 that can choose to access to view 1 and view 2 and office 2 that can access to the same views. When I click on view 1 for office 1, it triggers view 2 for office 2 also !

I click on view 1 for office 1, it selects view 1 for office 2 also

Here is the code :

<div >
        {
          //I take all the offices of a client
          officesArray.map((office, index) => {
            return (
              <div key={index}>
                <h3>site {(office.name)}</h3>
                <div key={index}>
                  //For each office I display the views available to select
                  viewsArray.map((view, index) => {
                    return (
                      <div>
                        <label
                          for={`${view.name}${office.name}`}
                        >
                          <input
                            key={`${index}${office.id}`}
                            type="checkbox"
                            id={`${view.name}${office.name}`}
                            name={`${view.name}${office.name}`}
                            value={`${view.name}${office.name}`}
                            checked={checkedState[index]}
                            onChange={() => handleOnChange(index, office.id)}
                          />
                          {view.name}
                        </label>
                      </div>
                    )
                  })}
                </div>
              </div>
            )
          })
        }
      </div>

And here is the handleonchange function :


const handleOnChange = (position, office) => {
    const updatedCheckedState = checkedState.map((item, index) =>
      index === position ? !item : item
    );
    prop.set({ id: (prop.views)[position].id_view, officeId: office })
    setCheckedState(updatedCheckedState);
  }





Aucun commentaire:

Enregistrer un commentaire