Jeffrey
Jeffrey

Reputation: 63

Using Map To Create Components - but functions are tied to each other

I am trying to create a bunch of dynamically filled dropdown menues.

unitMap = [[Unit1, Chapter1, Chapter2], [Unit2, Chapter3]]

let dropDownUnit = props.unitMap.map((unit, index) => {
    let unitName = unit[0];
    console.log(unit) // prints [Unit1, Chapter1, Chapter2] the first map, then [Unit2, Chapter3] the second map

    return (
        <List
          component="nav"
          aria-labelledby="nested-list-subheader"
          subheader={
              <ListSubheader component="div" id="nested-list-subheader" />
          }
          className={classes.root}
          key={index}
          >
              <ListItem button onClick={handleClick} >
                  <ListItemText primary={unitName} />
                  {!open ? <ExpandLess /> : <ExpandMore />}
              </ListItem>
              {/* {dropdownChap} */}
        </List>
    )
  })

This is the resulting render: What is displayed

It looks like the JSX is properly rendering the mapped components, but for some reason the onClick function is binded to both dropdowns, clicking either one of them will cause both/all dropdowns to collapse/expand. This defeats the purpose I am trying to achieve, by making all dropdowns independent from each other and I dont understand why this is happening.

Upvotes: 2

Views: 49

Answers (1)

Monique Altero
Monique Altero

Reputation: 76

The problem is that you only have one state control for all your items, you should have open controls for how many different items you want to control.

 <ListItem button onClick={handleClick} >
              <ListItemText primary={unitName} />
              {!open ? <ExpandLess /> : <ExpandMore />}
    </ListItem>

'open' is the same for all items.

My suggestion is to get the index and handle the click only for that current index.

<ListItem button onClick={handleClick(index)}
{!`open${index}` ? <ExpandLess /> : <ExpandMore />}

Upvotes: 4

Related Questions