0

I've found some relevant question but I need it for multiple div and couldn't find something that quite work.

Here I'm using the dropdown with checkbox from MUI. I am looking for a performant solution (And based on the other question doing a css class would be best but I've only been able to either turn all of them hidden or none(Not successfull at mapping one checkbox to one name)

I'm trying to toggle visibility, where if everything is checked then all the name show and if I uncheck "OliverHansen" Then that h3 with that name is hidden.

Here is the codesandbox: https://codesandbox.io/s/dropdown-checkbox-l467oq?file=/demo.tsx:840-2183

Thanks for any help!

export default function MultipleSelectCheckmarks() {
  const [personName, setPersonName] = React.useState<string[]>([]);

  const handleChange = (event: SelectChangeEvent<typeof personName>) => {
    const {
      target: { value }
    } = event;
    setPersonName(
      // On autofill we get a stringified value.
      typeof value === "string" ? value.split(",") : value
    );
  };


  return (
    <div>
      <FormControl sx={{ m: 1, width: 300 }}>
        <InputLabel id="demo-multiple-checkbox-label">Tag</InputLabel>
        <Select
          labelId="demo-multiple-checkbox-label"
          id="demo-multiple-checkbox"
          multiple
          value={personName}
          onChange={handleChange}
          input={<OutlinedInput label="Tag" />}
          renderValue={(selected) => selected.join(", ")}
          MenuProps={MenuProps}
        >
          {names.map((name) => (
            <MenuItem key={name} value={name}>
              <Checkbox
                defaultChecked
                checked={personName.indexOf(name) > -1} 
                inputProps={{ "aria-label": "controlled" }}
              />
              <ListItemText primary={name} />
            </MenuItem>
          ))}
        </Select>
      </FormControl>
      {names.map((name) => (
        <h3 key={name}>{name}</h3>
      ))}
    </div>
  );
}


Ikura
  • 188
  • 1
  • 11
  • you didn't really state which parts are working and which are not working. – Rick Mar 16 '23 at 15:42
  • @Rick Sorry I didn't want to add a bunch of comment in but I'll update it. But TL;DR I just couldn't figure out how to toggle visibility of a div based on a specific checkbox – Ikura Mar 16 '23 at 15:52

1 Answers1

1

Each time you set personName state, the component will re-render, adding or removing divs accordingly to what the contents of the array in the state.

Just loop through PersonName instead of names

{personName.map((name) => (
 <h3 key={name}>{name}</h3>
))}
Kakiz
  • 1,145
  • 1
  • 9
  • 18
  • 2
    Thank you! I don't know how I missed that .... For speed I used that pre made code but in reality I didn't have an array of name, I have an array of object. So I was able to do something like {Object.keys(allData.current).map((name) => ( personName.includes(name)?:"" ))} – Ikura Mar 16 '23 at 16:23