How to use button collapse with material ui accordion?

Viewed 7494

I'm using material UI for the collapse button, and the accordion. I want people to be able to click the today button, and have that open the first accordion section (the one that says Saturday on it). The today button is inside a material UI toolbar. I'm also using react hooks for the project.

I'm just using the default accordion settings as shown on the material UI website. Each accordion has its own id (ex: panel1, panel2, etc.).

I'm using the sample layout from material ui controlled accordion

Example of Open Accordions:

Image of my project's layout

Example of Closed Accordions:

My project with closed accordions

Any help you could give me would be great! Thanks.

1 Answers

Using the expanded property of the Accordion along with state will give you what you are looking for.

Be aware that once you set the expanded property, the default behavior of the accordion will be overridden and you will need to control the behavior directly.

Here's a code sandbox example of how I would solve it.

edit - code example:

import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Button
} from "@material-ui/core";
import React, { useState } from "react";
import "./styles.css";

const week = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday"
];

const d = new Date();
const currentDay = week[d.getDay()];

export default function App() {
  const [openDay, setOpenDay] = useState("");

  function handleAccordClick(day) {
    if(openDay === day) setOpenDay("")
    if(openDay !== day) setOpenDay(day)
  }

  function generateWeekAccordion(day) {
    return (
      <Accordion
        expanded={day === openDay}
        onClick={() => handleAccordClick(day)}
      >
        <AccordionSummary>{day}</AccordionSummary>
        <AccordionDetails>{`${day} details...`}</AccordionDetails>
      </Accordion>
    );
  }

  return (
    <div className="App">
      <Button
        style={{ marginBottom: "20px" }}
        variant="outlined"
        onClick={() => setOpenDay(currentDay)}
      >
        Open Today
      </Button>
      {week.map((day) => generateWeekAccordion(day))}
    </div>
  );
}
Related