Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Start Using the MUI Accordion Component

The accordion as an instrument is a portable, box-shaped instrument with a keyboard and bellows. It has a set of bellows that force air through metal reeds, producing notes. In software development, more especially, frontend development, an MUI accordion is a user interface (UI) component that allows users to hide or reveal content; an accordion is a type of menu that displays a list of headers stacked on top of one another.

When clicked on (or triggered by a keyboard interaction or screen reader), these headers will either reveal or hide associated content. It’s also known as an expansion panel.

Image Source – Medium

Accordion

An accordion component displays titles or headings in a one-below-the-other format. When a header is activated, it expands to showcase the related content section underneath it. It is a vertically stacked list of headers that reveal or hide associated sections of content.

Alternatively, the header can minimize to hide its associated section. This creates a collapsible effect that streamlines lengthy web page information.

Anatomy of an Accordion Component

An accordion has three main components; the header, the icon, and the panel.

  1. Header: The header contains the section title. The header also controls whether the content in the panel is visible or hidden.

  2. Icon: The icon shows if the panel is open or closed.

  3. Panel: The panel section shows the content related to an accordion header.

Anatomy of an Accordion Component

Image Source – Carbon Design System

States of an Accordion

The accordion has two primary states – collapsed and expanded. These dictate whether the panel (content) section below the header is shown or hidden.

A toggle icon (usually a chevron) visually indicates the state – pointing downwards when collapsed and upwards when expanded.

By default, accordions initialize fully collapsed, only displaying header summaries. This gives a high-level overview of available information before expanding down.

Users can expand multiple sections simultaneously as needed. The component allows individual control over each header/content pair.

Additionally, the headers have separate styles for when being hovered over or focused on by the keyboard, as well as a disabled state preventing user interaction. These various states and behaviors allow for flexible content display and interaction.

Overview of MUI

Material-UI, a React open-source library, offers a wide array of pre-designed components for creating modern and visually appealing web applications. One such essential component is the Accordion. This article delves into the fundamentals of Material-UI’s Accordion component, exploring its types, implementation, and customization.

Material UI is a popular open-source UI component library for React applications, following Google’s Material Design guidelines. It offers reusable, customizable components for building modern and visually appealing user interfaces. Material-UI v5 introduces numerous enhancements and new features, making it an excellent choice for front-end development.

With the release of Material UI version 5, you can harness its latest features and improvements.

Material UI logo

MUI was started in 2014 by Hai Nguyen and since then, it has experienced significant growth, boasting 89k+ stars on GitHub, 1.5M+ weekly downloads, with a small bundle size of 93.7kB (Minified + Gzipped).

The chart below from NPM trends compares the number of downloads of Material UI over the last year.

NPM Trends of MUI

If you use MUI for your project, consider using Purecode.ai Marketplace to access over 10000+ AI-generated ready-made templates and components to speed up your development process.

mWe will introduce the Accordion component and explain its role in allowing your website users to show and hide sections of related content on a page.

Finally, we will demonstrate how to integrate MUI accordion into our React application.

If you are new to Material-UI or looking to enhance your existing MUI skills, this article will provide you with the knowledge and hands-on examples you need to master the Accordion component.

By the end of this article, you will have the confidence to leverage the power of the Accordion component to create expandable content sections and responsive user interfaces in your React applications.

Introduction to the Accordion Component

The Accordion component is a generic building block that serves as a wrapper component for grouping other components. It’s a fundamental building block when building with MUI component libraries-you can think of it as a <div> with special features (like access to your app’s theme and the sx prop.

The Accordion component serves as a wrapper element for structuring and organizing your application’s layout. With the Accordion component, you can create containers, apply styling, manage spacing, and ensure responsiveness, making it a foundation for constructing visually appealing user interfaces.

The Accordion component in Material UI is very useful for styling elements in a React app. You can do so without using separate CSS files or the built-in makeStyles hook that is often used.

Implementing Material UI Accordion Component

Now you understand what Material UI library is, its significance, and why it is a preferred choice for most developers. Let’s learn how to install React and the MUI library.

Prerequisites

Before creating MUI tabs, you need to have the following:

  • NPM is installed on your machine.

  • Basic knowledge of JavaScript and React.

If you need help getting started with React, please check out the video tutorial below.

Setting up a React App

In your terminal, enter the following command to create a new React application:

npx create-react-app my-app && cd my-app

Once your app is set up, run the application by entering either of these commands in your terminal:

yarn start

Or using npm:

npm start

Your server should launch in your browser at http://localhost:3000/, as shown below:

React app

How to Install Material UI

To get set up with MUI we can install it as an NPM package or use Yarn.

npm install @material-ui/core

or

yarn add @material-ui/core

Once the MUI library is successfully installed, you are all set to start using the Material UI components in your React application.

Importing Material-UI Accordion Component

To import the Accordion component from MUI, use either of the following methods: default import or named import.

import Accordion from '@mui/material/Accordion';
// or
import { Accordion } from '@mui/material';

Next, import four accordion-related components:

  • AccordionGroup: A container that groups multiple accordions. It does not control the state of each accordion. You can provide a string value or an object to fine tune the animation at the initial and expanded states.

  • Accordion: A component that contains the expansion logic and sends it to AccordionSummary and AccordionDetails.

  • AccordionSummary: A header of the accordion that contains a button that triggers the expansion.

  • AccordionDetails: A wrapper for the accordion details.

import Accordion from '@mui/joy/Accordion';
import AccordionDetails from '@mui/joy/AccordionDetails';
import AccordionGroup from '@mui/joy/AccordionGroup';
import AccordionSummary from '@mui/joy/AccordionSummary';

How to Create a Basic Accordion Component with MUI

Putting everything we have imported so far, we will then have the following:

import * as React from 'react';
import AccordionGroup from '@mui/joy/AccordionGroup';
import Accordion from '@mui/joy/Accordion';
import AccordionDetails from '@mui/joy/AccordionDetails';
import AccordionSummary from '@mui/joy/AccordionSummary';

export default function AccordionBasic() {
  return (
    <AccordionGroup sx={{ maxWidth: 400 }}>
      <Accordion>
        <AccordionSummary>First accordion</AccordionSummary>
        <AccordionDetails>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
          tempor incididunt ut labore et dolore magna aliqua.
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary>Second accordion</AccordionSummary>
        <AccordionDetails>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
          tempor incididunt ut labore et dolore magna aliqua.
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary>Third accordion</AccordionSummary>
        <AccordionDetails>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
          tempor incididunt ut labore et dolore magna aliqua.
        </AccordionDetails>
      </Accordion>
    </AccordionGroup>
  );
}

The above code shows a basic accordion component:

Accordion Example

Types of MUI Accordions

Accordions enable customizable control over content sections. There are two primary types based on expanding behavior:

Uncontrolled – Operates independently without external direction. Sections can open or close based solely on user clicks. A component is uncontrolled when it’s managed by its own local state.

Controlled – State manipulated by the parent component. Expanded props allow programmatic control to show, hide, or lock sections.

Implementing Uncontrolled

Uncontrolled accordions function autonomously with user-driven interactions toggling sections. The example below demonstrates initializing a basic uncontrolled accordion where clicking headers reveals additional content.

import * as React from 'react';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import Typography from '@mui/material/Typography';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

export default function SimpleAccordion() {
  return (
    <div>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon/>}
        >
          <Typography variant='h4'>Item 1</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 1
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
        >
          <Typography variant='h4'>Item 2</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 2
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion >
        <AccordionSummary
          expandIcon={<ExpandMoreIcon/>}
        >
          <Typography variant='h4' >Item 3</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 3
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
        >
          <Typography variant='h4'>Item 4</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography variant='h5'>
            This section contains the collapsible content of item 4
          </Typography>
        </AccordionDetails>
      </Accordion>

    </div>
  );
}

Explanation of Imported Components

The Accordion component is brought in from @mui/material. This wraps around the summary and details sections.

Next, AccordionSummary is imported. This displays the heading content that can be clicked to expand.

Finally, AccordionDetails imports the collapsible area that shows additional content when open.

Note: The example demonstrates a controlled accordion where the state is handled externally instead of locally within the component. The parent manages visibility through expanded and onChange props rather than the internal state.

Implementing Controlled

Controlled accordions have state handling and behavior defined by the parent element. Passed props determine the expanded state.

import * as React from 'react';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import Typography from '@mui/material/Typography';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

export default function ControlledAccordion() {
  const [expanded, setExpanded] = React.useState(false);
  const handleChange = (acc) => (event, isExpanded) => {
    setExpanded(isExpanded ? acc : false);
  };

  return (
    <div>
      <Accordion expanded={expanded === 'acc1'} onChange={handleChange('acc1')}>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon/>}
        >
          <Typography variant='h4'>Item 1</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 1
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion expanded={expanded === 'acc2'} onChange={handleChange('acc2')}>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
        >
          <Typography variant='h4'>Item 2</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 2
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion expanded={expanded === 'acc3'} onChange={handleChange('acc3')}>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon/>}
        >
          <Typography variant='h4' >Item 3</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 3
          </Typography>
        </AccordionDetails>
      </Accordion>
    </div>
  );
}

Expanded State Handling

A state variable called expanded tracks whether an accordion is open or closed.

The handleChange method takes in the accordion key (acc) and updates the expanded based on the passed isExpanded boolean.

Control Props

The first accordion passes acc1 to handleChange and compares to expanded to show/hide content accordingly.

The second and third accordions work similarly, but check against acc2 and acc3 instead to independently manage each collapsed state.

So expanded and onChange allow external control to dictate visibility rather than internal component state. The parent component has full programmatic control over the expansion behavior.

The two types provide flexibility to choose whether accordion interactivity happens independently or under external direction.

Control Props

Importance of Accordions in Web Design

Accordions serve a valuable purpose in web design by streamlining page content and enhancing user experience. As websites become increasingly content-heavy, accordions provide an effective solution for presenting information in a condensed yet easily accessible format.

  • Streamline lengthy content – Accordions condense information under collapsible headers, preventing users from feeling overwhelmed by dense text.

  • Enhance accessibility – The ability to expand/collapse content caters to different user preferences for consuming information.

  • Improve content organization – Related content sections can be logically grouped under headers, facilitating understanding.

  • Allow flexible navigation – Users can easily navigate to sub-sections of interest rather than searching long pages.

  • Align with brand aesthetics – Accordions allow for customizable styling with colors, animations, etc. that match a brand’s visual identity.

  • Promote interactivity – Visually striking accordions entice users to toggle open the content sections.

  • Offer personalization – Both visual design and content presentation can be tailored to different target users.

  • Simplify complex pages – Condensing information into accordions simplifies lengthy or complex web pages.

  • Enhance user experience – All of the above drives higher engagement, satisfaction, and conversion for site visitors.

Understanding M-UI’s Accordion Component

The Accordion component is a powerful tool for organizing content in a user-friendly and visually pleasing manner. It simplifies complex web applications by presenting a list of items, each comprising a summary and a collapsible content section.

Check out this 8 mins video on everything you need to know about building accordions with MUI:

Accordion Types

Explore the two types of Accordions based on control over expanding sections:

Uncontrolled Accordion

Understand the operation of an Accordion without explicit control over its open and closed states. Implement the uncontrolled Accordion with code examples.

import * as React from 'react';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import Typography from '@mui/material/Typography';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

export default function SimpleAccordion() {
  return (
    <div>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon/>}
        >
          <Typography variant='h4'>Item 1</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 1
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
        >
          <Typography variant='h4'>Item 2</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 2
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion >
        <AccordionSummary
          expandIcon={<ExpandMoreIcon/>}
        >
          <Typography variant='h4' >Item 3</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 3
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
        >
          <Typography variant='h4'>Item 4</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography variant='h5'>
            This section contains the collapsible content of item 4
          </Typography>
        </AccordionDetails>
      </Accordion>

    </div>
  );
}


Controlled Accordion

Learn how to manage the Accordion using props passed by the parent component. Implement the controlled Accordion with code examples.

import * as React from 'react';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import Typography from '@mui/material/Typography';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

export default function ControlledAccordion() {
  const [expanded, setExpanded] = React.useState(false);
  const handleChange = (acc) => (event, isExpanded) => {
    setExpanded(isExpanded ? acc : false);
  };

  return (
    <div>
      <Accordion expanded={expanded === 'acc1'} onChange={handleChange('acc1')}>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon/>}
        >
          <Typography variant='h4'>Item 1</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 1
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion expanded={expanded === 'acc2'} onChange={handleChange('acc2')}>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
        >
          <Typography variant='h4'>Item 2</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 2
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion expanded={expanded === 'acc3'} onChange={handleChange('acc3')}>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon/>}
        >
          <Typography variant='h4' >Item 3</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 3
          </Typography>
        </AccordionDetails>
      </Accordion>
     
    </div>
  );
}


Color Customization

Discover how to customize the color of Accordions using the sx (styling attribute) and bgcolor (background color). Enhance the visual appeal of your Accordions with color customization.

import * as React from 'react';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import Typography from '@mui/material/Typography';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

export default function SimpleAccordion() {
  return (
    <div>
      <Accordion sx={{bgcolor:"blueviolet"}}>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon sx = {{color:'white'}}/>}
        >
          <Typography variant='h4' color={'white'}>Item 1</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5' color={'white'}>
            This section contains the collapsible content of item 1
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
        >
          <Typography variant='h4'>Item 2</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5'>
            This section contains the collapsible content of item 2
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion sx={{bgcolor:"blueviolet"}}>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon sx = {{color:'white'}}/>}
        >
          <Typography variant='h4' color={'white'}>Item 3</Typography>
        </AccordionSummary>
        <AccordionDetails>
        <Typography variant='h5' color={'white'}>
            This section contains the collapsible content of item 3
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
        >
          <Typography variant='h4'>Item 4</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography variant='h5'>
            This section contains the collapsible content of item 4
          </Typography>
        </AccordionDetails>
      </Accordion>

    </div>
  );
}


Steps to Make an Accessible Material UI (MUI) Accordion Component

  • Use Semantic HTML: Leverage the <details> and <summary> elements to provide native browser accessibility.

  • Add Descriptive Headings: Headings should communicate the content topic.

  • Ensure Keyboard Accessibility: Allow opening/closing the accordion via keyboard shortcuts.

  • Implement Focus Management: Manage focus movement to avoid trapping keyboard users.

  • Provide ARIA Controls Attributes: Use aria-expanded and aria-controls for added context.

  • Allow Text Resizing: Don’t set fixed heights/widths that prevent text resizing.

  • Test Assistive Technology Compatibility: Verify screen reader and keyboard navigation compatibility.

  • Follow Color Contrast Standards: Pass WCAG 2.1 minimum 4.5:1 contrast ratio.

  • Add Animations and Transitions Carefully: Ensure they don’t create issues for sensitive users.

  • Allow Accordion State Saving: Retain opened/closed state through refreshes.

Following these steps will help create an inclusive MUI accordion that works well for all users. Let me know if you need any clarification or have additional questions!

For an even more in-depth video tutorial on the MUI accordion, check out this 20 minutes video tutorial on YouTube:

Tabular Comparison of Key Aspects of Material UI Accordion Component

FeatureDescription
Installationnpm install @mui/material @emotion/react @emotion/styled
Importimport Accordion from '@mui/material/Accordion';
Basic UsageWrap content sections in <Accordion> tags with <AccordionSummary> for headings
Expand BehaviorDefault collapsed, click headers to expand. Use an expanded prop to control the state
Multiple SectionsAllow multiple sections to open simultaneously
CustomizationHeader typography, colors, spacing, etc. via MUI props like sx
AccessibilitySemantic HTML, keyboard navigation, ARIA attributes
PerformanceLightweight, fast rendering with Virtualization
DocumentationExtensive docs & examples at mui.com/components/accordion

Some key points of comparison when getting started:

  • Easy to install and import components from @mui/material
  • Straightforward to add basic collapsible sections
  • Flexible control over expanded state and behavior
  • Lots of built-in customization options
  • Optimized for accessibility
  • Blazing-fast performance with Virtualization
  • Thorough documentation and examples

Accessibility with MUI Accordion

The built-in accessibility of the accordion follows WAI-ARIA Authoring Practices.

  • The accordion summary has a root slot (div) that can be changed, for example using h3, based on the hierarchy of the accordion.

  • The accordion summary contains a button with aria-expanded and aria-controls attributes.

  • The accordion details contain a div with role=”region” and aria-labelledby attributes.

Wrapping Up

Material-UI’s Accordion component serves as a valuable tool for improving content presentation and enhancing user experience in web applications. By effectively organizing and managing complex information, developers can leverage the Accordion component to create more intuitive and visually pleasing interfaces. Start incorporating Material-UI’s Accordion into your React applications to elevate the user experience.

If you want to be a 5x developer and skip the hard part of building UIs from scratch, Purecode.ai has a repository of 10,000+ custom-generated AI components for MUI, TailwindCSS, and CSS3. Consider using our AI-generated custom components today!

Further Readings

Check out this article worthy of read if you enjoyed reading this piece:

Emmanuel Uchenna

Emmanuel Uchenna

Emmanuel is an experienced and enthusiastic software developer and technical writer with 4+ proven years of professional experience. He focuses on full-stack web development. He is fluent in React, TypeScript, VueJS, and NodeJS and familiar with industry-standard technologies such as version control, headless CMS, and JAMstack. He is passionate about knowledge sharing.