Home > front end >  How to keep MUI accordion from expanding?
How to keep MUI accordion from expanding?

Time:05-03

i'm using two components from MUI, accordion and Modal. I have the Modal on the accordion summary, but when i open it, everytime i click inside the modal, the accordion also receives the interaction, thus it expands. I passed the open state of Modal to the Accordion, and tried changing things based on the open state. Like

pointerEvents:`${open == true? 'none': 'auto'}`

Tried something like this with disabled, but it remains the same. I have a sample of the code here https://stackblitz.com/edit/react-ts-zer8p7?file=accordion.js

Thanks in advance

CodePudding user response:

The issue here is that your click event is bubbling up the component tree until it is consumed by the accordion summary. You can stop this anywhere in the hierarchy by using the event stopPropagation function. You could change your BaseModal component to something like so:

export default function BasicModal() {
   const [open, setOpen] = React.useState(false);
   const handleOpen = () => setOpen(true);
   const handleClose = () => setOpen(false);

   const onModalClick = (e) => {
      e.stopPropagation();
   };
  
   return (
      <div onClick={onModalClick}>
         <Button onClick={handleOpen}>Open modal</Button>
         <Modal
             open={open}
             onClose={handleClose}
             aria-labelledby="modal-modal-title"
             aria-describedby="modal-modal-description"
         >
            <Box sx={style}>
               <Typography id="modal-modal-title" variant="h6" component="h2">
                  Text in a modal
               </Typography>
               <Typography id="modal-modal-description" sx={{ mt: 2 }}>
                  <TemporaryDrawer />
               </Typography>
            </Box>
         </Modal>
      </div>
    );
}

The onModalClick receives the click event and stops it from propagating up the component tree to the accordion summary.

  • Related