Achieving Full Height for React Material-UI Accordion

I have 2 Material-ui Accordions that I want to customize in terms of height expansion. Here are the three scenarios I am aiming for:

  • Both accordions start in a collapsed state.
  • One accordion stays collapsed while taking up the maximum available height.
  • Both accordions expand fully, each taking up 50% of the total height.

I've attempted to achieve this using CSS properties such as flex-grow and flex-direction: column, but haven't been successful so far.

To better understand my code implementation and issue, you can view it on CodeSandbox through this link: https://codesandbox.io/s/upbeat-tesla-uchsb?file=/accordionFullHeight

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Accordion from '@material-ui/core/Accordion';
import AccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';

const useStyles = makeStyles((theme) => ({
  root: {
    width: '100%',
    background: 'green',
    height: '90vh'
  },
  heading: {
    fontSize: theme.typography.pxToRem(15),
    fontWeight: theme.typography.fontWeightRegular,
  },
}));

export default function SimpleAccordion() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <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>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls="panel2a-content"
          id="panel2a-header"
        >
          <Typography className={classes.heading}>Accordion 2</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>
    
    </div>
  );
}

Answer №1

Successfully tackled the issue by utilizing a controlled Accordion that employs flex-grow:1 only when expanded:

Link to code sandbox

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Accordion from "@material-ui/core/Accordion";
import AccordionDetails from "@material-ui/core/AccordionDetails";
import AccordionSummary from "@material-ui/core/AccordionSummary";
import Typography from "@material-ui/core/Typography";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";

const useStyles = makeStyles((theme) => ({
  root: {
    width: "100%",
    background: "red",
    color: "blue"
  },
  rootExpanded: {
    background: "blue",
    flexGrow: 1
  }
}));

export default function MyAccordion(props) {
  const classes = useStyles();
  const { name } = props;
  const [expanded, setExpanded] = React.useState(false);

  const rootClass = expanded ? classes.rootExpanded : classes.root;

  const handleChange = (panel) => (event, isExpanded) => {
    setExpanded(isExpanded ? panel : false);
  };

  return (
    <Accordion
      className={rootClass}
      expanded={expanded === name}
      onChange={handleChange(name)}
    >
      <AccordionSummary
        expandIcon={<ExpandMoreIcon />}
        aria-controls="panel1bh-content"
        id={`${name}-header`}
      >
        <Typography className={classes.heading}>General settings</Typography>
        <Typography className={classes.secondaryHeading}>
          I am an accordion
        </Typography>
      </AccordionSummary>
      <AccordionDetails>
        <Typography>
          Nulla facilisi. Phasellus sollicitudin nulla et quam mattis feugiat.
          Aliquam eget maximus est, id dignissim quam.
        </Typography>
      </AccordionDetails>
    </Accordion>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Firefox displays a smaller right margin when using CSS layout in percentage units

As I work on scripting some CSS, I have come across a small challenge where the right margin seems smaller than the left one despite both being set at 5%! This issue is occurring while using Firefox version 35.0.1. body { width: 100%; padding: 0; ...

Retrieving and sending data within a redux action function

I am encountering an issue in my react/redux project where I am trying to call a function from my action to fetch data from an API. However, when the fetch is initiated, React does not recognize dispatch. function getAuthenticatedUser() { .... re ...

Is it possible to authenticate across multiple tables in a React/Node.js environment?

I am currently planning an online library management system project. For this project, I have identified **3 distinct roles** which are stored in separate database tables. Firstly, there is the user role, which will have an interface allowing them to view ...

The second entry is not being styled by CSS, is there an issue with the code in this section?

I am facing a challenge while trying to set the same background image for two div elements: .abc { background: url('images/autogen.png') no-repeat 0px -133px; width: 256px; height: 256px; }; .def { background: url('images/autogen.png' ...

The screen orientation does not update on iOS when using react-native-webview

I've been working on a small react-native app that mainly acts as a container for displaying my webapp. Everything is running smoothly except for one issue. The problem arises when the user needs to rotate the screen on certain pages of the webapp. W ...

`The toggleClass function will only respond to the first click in Internet Explorer and Firefox browsers

This is my first time asking for help as I usually find the answers myself, but this issue has me stumped. Here's what I have: HTML <!-- This div opens/shows the navigation. I need to change the div to a button tag --> <div class="menu"> ...

Adjust the color of the bootstrap navbar upon resizing the screen

Attempting to modify the background color for the navbar menu items on smaller screen sizes. An issue arises in the following scenario: Browser window is resized until hamburger menu appears Hamburger menu is clicked to display menu i ...

Firefox keeps track of the state of page elements

I have noticed that Firefox seems to retain the css state of my webpage's elements. Even after reloading, it still remembers things like the content in a div that was previously modified and the visibility settings of specific elements. Is there a way ...

Unable to modify the border color of the outline in MUI text fields

I am currently working on a React project using MUI and styled-components, but I am facing an issue with changing the outline border color of a textfield. Despite reading the documentation and attempting to overwrite the class names of the component, it do ...

Approaching fashion from a new angle: incorporating perspective into

How can I style elements in the perspective to appear straight(3d) instead of flat due to perspective? I want to achieve a design where the alphabets and flag post image align perfectly. https://i.sstatic.net/HcHMC.jpg .container { perspective: 100p ...

What's the best way to align several buttons in the center of the screen horizontally?

I'm struggling to properly align divs with images inside another div. My goal is to insert buttons into my HTML and use jQuery to center them automatically, but I can't seem to get it right. You can view the fiddle I've created here: http:/ ...

Failure to capture spaces in onChange events for <input> elements

I'm having an issue where the onChange event is not being called on my HTML input element when pressing the space bar. Here's a snippet of what I've tried: class FilterDropDown extends React.PureComponent { state = { query: '&ap ...

Set the width of the left div in percentage and have the right div automatically fill

In my layout, I have a left div with a percentage width floating to the left, and a right div also floating left that should take up the remaining space. Here is a [fiddle] link for reference: https://jsfiddle.net/gfhfku8k/. Any assistance would be great ...

Learn the process of crafting a higher order function within a functional component in React

I am currently working on creating a high-order component using React functional component, but I seem to be encountering an issue where I am not receiving the props value in the passed component. I am also incorporating TypeScript into my project. This i ...

What is the best way to print out multiple objects using console.log?

I am working on a JavaScript exercise where I want to create a function that produces an icon output using FontAwesome. While I have managed to display the icon and message, I am struggling to incorporate my custom styles for titles, emphasis, etc., using ...

npm encountered a problem resolving packages related to ESLint

Encountered npm error code ERESOLVE while trying to resolve dependencies. The error message indicates issues with resolving certain packages, such as @typescript-eslint/eslint-plugin and eslint-config-react-app. The root of the problem seems to be conflic ...

Creating a simple vertical layout with a fixed header and footer using basic HTML and CSS, allowing for easy stretching and customization

Looking for advice on creating a vertical layout with a static height header and footer, while allowing the center to occupy all available space and adjust to the window height. header ------ center ------ footer Any suggestions would be greatly appr ...

Establishing flow types and generating unchangeable records

Looking to integrate Flow with Immutable.js Records, I've set up my record like this: const MyRecord = new Immutable.Record({id: undefined}) Now when I create records using new MyRecord({id: 1}), Flow gives me an error: constructor call Construct ...

The asynchronous function is not being executed by onSubmit

I am attempting to create a function that will generate a gif when the "get gif" button is pressed. However, I am facing an issue where nothing shows up in the console and the page reloads. 1) The requirement is for the client to enter a value 2) Set th ...

Dynamically generate a new array every time a numeral is encountered within the Input Array in JavaScript

I'm facing a dilemma. I have an array with user input that contains both numbers and strings, like this:- 3 apple Lemmon sugar 2 Ginger Ice This is the data I'm working with. My task is to manipulate the data so that "Whenever it encounters a n ...