Home > front end >  Toggle to display separately
Toggle to display separately

Time:03-15

I want to individually toggle the list..how should it be proceeded?

 .map((item) => {
                    return (
                   <>
                       <StyledTableRow key={item.medName}>
                      <button onClick={() => setToggle(!toggle)}>
                        <StyledTableCell component="th" scope="row">
                          {item.medName}
                        </StyledTableCell></button>
                        {toggle && <StyledTableCell align="center" >
                          {item.saltName}
                        </StyledTableCell>
                      </StyledTableRow>
                      </>

CodePudding user response:

Instead of storing a single boolean state value for every element, store an id or some other unique property that can be independently set/checked.

Example:

const [toggled, setToggled] = React.useState({});

const toggleHandler = id => {
  setToggled(ids => ({
    ...ids,
    [id]: !ids[id], // <-- toggle specific element by key
  }));
};

...

.map((item) => {
  return (
    <>
      <StyledTableRow key={item.medName}>
        <button onClick={() => toggleHandler(ite.medName)}> // <-- pass property
          <StyledTableCell component="th" scope="row">
            {item.medName}
          </StyledTableCell>
        </button>
        {toggle[item.medName] && ( // <-- check property
          <StyledTableCell align="center">
            {item.saltName}
          </StyledTableCell>
        )}
      </StyledTableRow>
    </>
  );
})
  • Related