Search code examples
reactjsmaterial-uiaccordion

Removal of AccordianDetails component from DOM on collapse of material-ui Accordian


I am using Accordion component of material-ui in my first React project. I noticed that when the Accordion is collapsed, the AccordionDetails(being descendent of Collapse) is not removed from the DOM. It is only hidden away by changing the height internally. My code is:

<Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls="panel1a-content"
          id="panel1a-header"
        >
          <Typography className={classes.heading}>Accordion 1</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex,
            sit amet blandit leo lobortis eget.
          </Typography>
        </AccordionDetails>
      </Accordion>

and in React Developer Tools it looks like this:

Accordion
  Accordion.ContextProvider
    AccordionSummary
      ButtonBase
  Collapse
    Transition
      Context.Provider
        AccordionDetails
....

How can I collapse the Accordion removing the AccordionDetails from the DOM and with the default transition?

I could not find any option to do this in Collapse and Accordion API documentation.

Currently installed version:

  • react: 16.12.0
  • material-ui: 4.9.1

Solution

  • The component used for the collapse effect or the TransitionComponent is the Collapse component and by default the child component stays mounted after it reaches the 'exited' state. We can pass props to it by using TransitionProps.

    The following code will unmount the AccordionDetails component being a child component of Collapse when Transition reaches the exit state or simply when Accordion is collapsed.

    <Accordion TransitionProps={{ unmountOnExit: true }}> 
    

    Reference: http://reactcommunity.org/react-transition-group/transition#Transition-prop-unmountOnExit