'Material UI / React - close accordion onSubmit

I have a form within an accordion - what I want to do is when the form is submitted collapse the accordion.

<Accordion elevation={3}>
<AccordionSummary expandIcon={<ExpandMoreIcon />} aria-controls="panel1a-content" id="panel1a-header">
</AccordionSummary>
<AccordionDetails>
<form onSubmit={onSubmit}>
</form>
</AccordionDetails>
</Accordion>

const onSubmit = e => {
    e.preventDefault();
    firebase
      .firestore()
      .collection("meals")
      .add({
        Name : name,
      })
      //.then will reset the form to nothing
      .then(() => setName("");
  };

Ideally in the .then of the firebase add I would collapse the accordion from there.



Solution 1:[1]

You can set the expanded prop of the Accordion when submiting the form.

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


<Accordion expanded={expanded} > </Accordion>

When submiting the form , you have to set the prop to false

const submit = () => {

// ...
setExpanded(false);
}

Acording to your need , this is example which make you do the job :

code example on sandbox here

So the point here is to call the same function handleChange with a string(panel name) different to the ones given to each accordion.

Hope this help you.

Solution 2:[2]

Crete an “expanded” Boolean state variable and bind it to the expanded props of the accordion https://mui.com/api/accordion/

Then, set this state variable to false in your “then” callback.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Plumpie
Solution 2 Paul Serre