Mote Zart
Mote Zart

Reputation: 960

Material-UI Expansion Panel not obeying controled expansion

I want the first of the three expansion panels to be open but still only allow one panel at a time to be open. Currently I can either have the first panel open OR have the panels controlled to be open one a time, but not both. But this what I need.

I also need the jsx to be rendered with a loop. This loop seems to be be causing the issue because this works without a loop.

The 2nd and 3rd drawers works as they should here.

I've tried passing the the props directly like in the docs but this did not work. Currently I am trying to pass them in dynamically so only the proper props ones go with each panel, with each iteration of the loop. It looks like this:

function setAttributes(i) {
   return [
     { defaultExpanded: true },
     { expanded: expanded === `panel2` },
     { expanded: expanded === `panel3` }
   ]
  }

return (
<div className={`${classes.root} accordion`}>
  {Object.values(props.drawers).map((drawer, i) => {
    return (
      <ExpansionPanel
        key={i} 
        //set attributes here
        {...setAttributes(i)[i]}
        onChange={handleChange(`panel${i + 1}`)}
        className="expansion-panel"
      >
        <ExpansionPanelSummary
          className="expansion-panel-inner"
          expandIcon={<ExpandMoreIcon />}
          aria-controls={`panel${i + 1}bh-content`}
          id={`panel${i + 1}bh-header`}
        >
          <Typography className={`${classes.heading} panel-heading`}>
            {' '}
            {drawer.heading}
          </Typography>
          <Typography className={classes.secondaryHeading} />
        </ExpansionPanelSummary>
        <ExpansionPanelDetails>
          <Typography>{drawer.text}</Typography>
        </ExpansionPanelDetails>
      </ExpansionPanel>
    )
  })}
</div>

)

I've tried looking at what props are attached after render but its' not super clear; it's not as easy as looking for an added class. It's unclear to me if the proper props are getting added to each panel. I also tried making the first object inside setAttributes { defaultExpanded: true, expanded: expanded === "panel1" }, but this just disables the default expansion.

A demo shows the problem.

I want the first panel open on load, then after that only one panel, whichever is clicked, to be open, and only that one.

Upvotes: 3

Views: 5213

Answers (1)

Anthony Z
Anthony Z

Reputation: 394

If I'm understanding your issue, you should be able to just set the default value.

const [expanded, setExpanded] = React.useState("panel1");

And if you want to make it so you can't collapse a panel by clicking it again:

const handleChange = panel => (event, isExpanded) => {
    setExpanded(panel);
};

Upvotes: 3

Related Questions