import React, { useState } from "react";
import {
Accordion,
AccordionDetails,
AccordionSummary,
Typography
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
export default function DetailedAccordion() {
const [expanded, setExpanded] = useState(null);
const handleChange = (panel) => (event, isExpanded) => {
setExpanded(isExpanded ? panel : false);
};
return (
<div>
<Accordion defaultExpanded
expanded={expanded === "panel1"}
onChange={handleChange("panel1")}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1bh-content"
id="panel1bh-header"
>
<Typography>Accordion Panel 1</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae
elit libero, a pharetra augue.
</Typography>
</AccordionDetails>
</Accordion>
<Accordion
expanded={expanded === "panel2"}
onChange={handleChange("panel2")}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel2bh-content"
id="panel2bh-header"
>
<Typography>Accordion Panel 2</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae
elit libero, a pharetra augue.
</Typography>
</AccordionDetails>
</Accordion>
<Accordion
expanded={expanded === "panel3"}
onChange={handleChange("panel3")}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel3bh-content"
id="panel3bh-header"
>
<Typography>Accordion Panel 3</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae
elit libero, a pharetra augue.
</Typography>
</AccordionDetails>
</Accordion>
</div>
);
}
I want all panels to be non-closable. One should always remain open.
Tried the code above but somehow again I can close them all.
Whichever one I leave open I can’t close until a new one opens.
All of them are closing on me all the time. One must be open.
Someone help how to solve this.
Here is a demo here. codesandbox.io
2
Answers
An easy solution would be to store the state of each accordion in the state of the component.
Perhaps something like this? CodeSandbox Example Here