Type to generate UI components from text

OR

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

Explore Components

Building a Great Tailwind Accordion Component in React

Photo by Lautaro Andreani on Unsplash

Introduction to React Accordion

A React accordion is a user interface component (and design system) that allows you to organize and display content in a collapsible and expandable manner. It consists of a list of items with a header (often a title) and a content section. Users click on the item’s header to expand or collapse the associated content.

They are handy for presenting a lot of information without overwhelming your users. Combining the power of React with the utility-first styling of Tailwind CSS allows you to create dynamic and responsive accordion styles, easily customized to suit your project’s needs. This guide walks you through building an accordion in a React application with Tailwind.

Check out purecode.ai for more development-ready codes to speed up your release cycles.

Here’s how an accordion typically works:

  • Initially Closed: When a web page or interface loads, the sections are usually closed or collapsed, displaying only summary information or headings.

  • User Interaction: When a user clicks or interacts with a particular section or element, it expands to reveal the accordion body, which includes more detailed information or sub-sections. It can include text, images, forms, or other content.

  • Multiple Sections: Users can often interact with diverse sections independently, opening and closing them as needed. i.e. if you have, say, three accordions, the user may open the first item’s accordion body whilst the second and third item’s accordion body remain closed. This allows the user to access whichever information is needed, one at a time.

  • Space Efficiency: The accordion effect is handy when there’s a need to organize a lot of content in a structured manner without overwhelming the user.

Here is a simple working code example of a React Accordion (without Tailwind)

import React, { useState } from 'react';

function AccordionItem({ title, content, isOpen, toggleAccordion }) {
  return (
    <div className="border border-gray-300 rounded mb-2">
      <div
        className="p-2 cursor-pointer flex justify-between items-center text-gray"
        onClick={toggleAccordion}
      >
        <h2>{title}</h2>
        {isOpen ? <span>▲</span> : <span>▼</span>}
      </div>
      {isOpen && <div className="p-2">{content}</div>}
    </div>
  );
}

function Accordion() {
  const [accordionItems, setAccordionItems] = useState([
    {
      title: 'What is a CPU?',
      content: 'Central Processing Unit',
      isOpen: false,
    },
    {
      title: 'What is the full meaning of CSS?',
      content: 'Cascading Style Sheet',
      isOpen: false,
    },
    {
      title: 'Find the value of "X" here.',
      content: '"X" is definitely something.',
      isOpen: false,
    },
  ]);

  const toggleAccordionItem = (index) => {
    const updatedAccordionItems = [...accordionItems];
    updatedAccordionItems[index].isOpen = !updatedAccordionItems[index].isOpen;
    setAccordionItems(updatedAccordionItems);
  };

  return (
    <div>
      {accordionItems.map((item, index) => (
        <AccordionItem
          key={index}
          title={item.title}
          content={item.content}
          isOpen={item.isOpen}
          toggleAccordion={() => toggleAccordionItem(index)}
        />
      ))}
    </div>
  );
}

export default Accordion;

There are two components: AccordionItem for each accordion item (question and answer) and Accordion, to manage multiple accordions.

Check out Brian’s teaching on React Accordion via YouTube.

How to build an accordion component from scratch– FreeCodeCamp

Understanding the Accordion Pattern

At first glance, the Accordion pattern seems like the musical accordion.

Here, it is a functional design system, handy when dealing with large amounts of information or when you want to create a structured, expandable interface.

Key Characteristics of the Accordion Pattern

Before we dive into code samples, let’s establish the vital characteristics of the accordion pattern:

  • Header-Content Structure: An accordion consists of a series of items, each comprising a header and a content section. The header is a clickable label or title, while the content contains detailed information.

  • Collapsible Sections: Only one content section is visible at a time. Clicking on a header expands its associated content while collapsing any other open content sections. It provides a clean and organized layout.

  • User Interaction: Users interact with the accordion body by clicking the headers. This action triggers the expansion or hiding sections of the associated content section, providing a user-friendly way to navigate the information.

  • Space Efficiency: An accordion is space-efficient since it displays only a summary or title for each section by default. Users can choose to reveal the accordion body and view more details when needed.

Benefits and Use Cases of the Accordion Pattern

The accordion pattern offers several benefits:

  • Efficient use of screen space: It saves screen real estate by displaying only one section at a time. Organized content: It helps organize content into manageable sections.

  • Progressive disclosure: It allows users to access more details only when needed.

  • Improved user experience: It provides an intuitive and interactive way to navigate content.

Common use cases for the accordion pattern include;

  • FAQs,

  • Product descriptions,

  • Documentation, etc.

Prerequisites

  • Basic understanding of Tailwind and React

  • Node.js and npm (Node Package Manager) installed on your system.

  • A code editor (Visual Studio Code)

Setting Up the Project

Set up a new React project using Create React App:

npx create-react-app tailwind-accordion
cd tailwind-accordion
npm start

It will create a basic React application running at http://localhost:3000/.

Installing Tailwind CSS

Next, install Tailwind CSS and its dependencies:

npm install tailwindcss postcss-cli autoprefixer

Generate the necessary configuration files with,

npx tailwindcss init -p

It will create tailwind.config.js, postcss.config.js, and a CSS folder.

Creating the Accordion Component

Create a new file for the Accordion component:

src/components/Accordion.js

Structuring the Component

The Accordion component consists of a series of items with a title and content. Here’s a basic structure:

import React, { useState } from 'react';

const Accordion = ({ items }) => {
  // State to track which accordion item is active
  const [activeIndex, setActiveIndex] = useState(null);

  // Function to toggle accordion item
  const toggleAccordion = (index) => {
    setActiveIndex(index === activeIndex ? null : index);
  };

  return (
    <div>
      {items.map((item, index) => (
        <div key={index}>
          {/* Accordion header */}
          <div onClick={() => toggleAccordion(index)}>
            {item.title}
          </div>
          {/* Accordion content */}
          {activeIndex === index && (
            <div>
              {item.content}
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

export default Accordion;

The reusable React component is the Accordion; It creates an accordion-style user interface based on an array of items passed as a prop. It maintains the open/closed state of each accordion item using React’s useState hook and allows users to toggle the visibility of item content by clicking on the item headers. The click of the header displays the associated content or hides it based on the item’s active state.

Adding State for Accordion Functionality

The React useState hook manages the state of our accordion component. The `activeIndex` state variable tracks the accordion item currently active (open). Initially, it’s set to null, indicating no items are open.

import React, { useState } from 'react';

const Accordion = ({ items }) => {
  // State to track which accordion item is active
  const [activeIndex, setActiveIndex] = useState(null);

Implementing the Accordion UI

The Accordion component iterates through the items prop an array of objects with title and content properties. For each item, it renders a clickable header. If the `activeIndex` matches the item’s index, it displays the content.

Styling the Accordion Header

Style the Accordion component. You can apply classes like bg-gray-200, text-lg, font-semibold, p-4, and cursor-pointer to style the accordion header:

// ...
<div
  onClick={() => toggleAccordion(index)}
  className="bg-gray-200 text-lg font-semibold p-4 cursor-pointer flex items-center justify"
>
  {item.title}
</div>
// ...

Styling the Accordion Content

To style the accordion content, use classes like hidden, p-4, border, border-gray-300, and transition:

// ...
<p class={`p-4 border border-gray-300 transition ${activeIndex === index ? '' : 'hidden'}`}>
  {item.content}
</p>
// ...

Toggling Accordion Items

The `toggleAccordion` function is responsible for toggling the accordion item. By clicking an item’s header, it checks if the clicked item is already open (activeIndex === index). If yes, it closes it by setting `activeIndex` to null. Otherwise, it sets `activeIndex` to the index of the clicked item.

// Function to toggle accordion item
  const toggleAccordion = (index) => {
    setActiveIndex(index === activeIndex ? null : index);

Adding Tailwind CSS Transitions

To create smooth transitions when opening and closing an accordion item, apply the transition class. This class adds CSS transitions to expand and collapse the content section when its visibility changes.

Here’s how you can add the transition class to the accordion content:

<div className={`p-4 border border-gray-300 ${activeIndex === index ? 'transition' : 'hidden'}`}>
  {item.content}
</div>

The transition class adds when the accordion content is active (open). When the content becomes visible or hidden, it smoothly transitions its height and opacity, creating a visually appealing effect.

Handling Multiple Accordions

In most cases, you may have multiple accordions on a single page or within different sections. Follow these approaches to resolve;

  • Option 1: Separate Components: Create separate Accordion components for each set of items. Each Accordion component will manage its state independently. This approach is suitable when different sections of your application require distinct accordions.

  • Option 2: Unique Identifiers: Assign unique identifiers or keys to each item in your items array. Then, modify the toggleAccordion function to accept an item identifier instead of an index. It allows you to differentiate an accordion item based on its identifiers.

Here’s an example modification to the `toggleAccordion` function:

const toggleAccordion = (itemId) => {
  setActiveItem(itemId === activeItem ? null : itemId);
};

The activeItem represents the identifier of the currently active item. Clicking an item identifier determines whether to open or close it.

The choice between these options depends on your specific use case. Option 1 provides more isolation between accordion sets, while Option 2 allows a more dynamic approach when managing multiple accordions within the same component.

Customizing the Accordion

Tailwind CSS offers extensive customization capabilities, allowing you to tailor the appearance of your accordion to match your project’s design and branding. To customize the accordion’s appearance, modify the Tailwind CSS configuration in the tailwind.config.js file.

Here’s an example with colors in your tailwind.config.js file:

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        primary: '#3490dc',
        secondary: '#ffed4a',
      },
    },
  },
  variants: {},
  plugins: [],
};

The color palette extends with custom primary and secondary colors. You can customize fonts, spacing, breakpoints, and other design aspects by adjusting the Tailwind CSS configuration to align with your project’s design requirements. Tailwind CSS’s flexibility in customization ensures that your accordion components can seamlessly integrate into your application’s overall design and branding.

The accordion component is all set; you can set up other desired configurations.

How to Collapse in Tailwind CSS

Collapsing elements using Tailwind CSS typically involves toggling the hidden class, which sets the display property of an element to none, and toggling the block class to show it. Use the transition class to provide smooth animations if desired.

Here’s a step-by-step code example of creating a simple collapsing element in Tailwind CSS (HTML, CSS, JavaScript):

  • HTML Element: Start with the HTML element structure for your collapsing element. For example, you can use a div element to collapse and a button element to trigger the collapse effect.

<div class="w-64 bg-gray-200 p-4 transition-all duration-300" id="collapsible">
  <!-- Content goes here -->
</div>

<button id="toggleButton" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
  Toggle Collapse
</button>

It has a div with the bg-gray-200 background color and a button with the text “Toggle Collapse.”

  • Tailwind CSS Classes: Apply the necessary Tailwind CSS classes to style your elements and set up the initial state. In this example, w-64 (width), bg-gray-200 (background color), and p-4 (padding) will style the collapsible element.

  • JavaScript for Toggling: Toggle the hidden class on the collapsible element when the user clicks the button. (You can achieve this using plain JavaScript or a JavaScript framework like React.)

const collapsibleElement = document.getElementById('collapsible');
const toggleButton = document.getElementById('toggleButton');

toggleButton.addEventListener('click', () => {
  collapsibleElement.classList.toggle('hidden');
});

The JavaScript code got references to the collapsible element and the button. It added a click event listener to the button. Clicking the button toggles the hidden class on the collapsible element.

  • Transition Effects (Optional): If you want to add smooth transition effects to the collapsing element, use the transition class (you can also use diverse custom styles). This class will animate the element’s height and opacity when it’s hidden or shown. Add the duration-300 class to control the duration of the animation.

<div class="w-64 bg-gray-200 p-4 transition-all duration-300" id="collapsible">
  <!-- Content goes here -->
</div>

In this example, the transition-all and duration-300 classes achieve a smooth collapse animation over a 300-millisecond duration. (Adjust the timespan to your preference.)

Using React

In React, you use the state to control the element visibility and Tailwind CSS classes to toggle its appearance.

A simple example to create a collapsing element in Tailwind CSS with React:

1.Set Up a React Project: If you haven’t already, create a new React project or navigate to an existing one using a tool like Create React App.

npx create-react-app tailwind-collapse cd tailwind-collapse npm start 

2. Install Tailwind CSS:

Install Tailwind CSS and its dependencies using npm:

npm install tailwindcss postcss-cli autoprefixer Generate the necessary configuration files:npx tailwindcss init -p 

It will create the tailwind.config.js and postcss.config.js files.

3. Create a React Component:

Create a new React component to contain the collapsible element. (Collapsible.js):

// Collapsible.js import React, { useState } from 'react'; const Collapsible = () => {   // The collapse state tracking   const [isCollapsed, setIsCollapsed] = useState(true);   // Function to toggle the collapsed state   const toggleCollapse = () => {     setIsCollapsed(!isCollapsed);   };   return (     <div>       <button         className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"         onClick={toggleCollapse}       >         Toggle Collapse       </button>       <div         className={`${           isCollapsed ? 'hidden' : 'block'         } w-64 bg-gray-200 p-4 transition-all duration-300`}       >         {/* Collapsible content */}         Content goes here       </div>     </div>   ); }; export default Collapsible; 

We use the useState hook to create a isCollapsed state variable that tracks if the element collapses. The toggleCollapse function toggles the value of the isCollapsed clicked button. In the JSX, we render a button that, when clicked, calls toggleCollapse to toggle the state. We use conditional rendering to apply the hidden or block class to the collapsible element based on the isCollapsed state.

The Tailwind CSS classes like w-64, bg-gray-200, p-4, transition-all, and duration-300 are applied to style the collapsible element and provide a smooth transition effect.

4. Use the Component:

You can now use the Collapsible component within your application. Import it into your desired component file and include it in your JSX:

// App.js import React from 'react'; import Collapsible from './Collapsible'; function App() { return ( <div className="App"> <h1>Collapsible Element Example</h1> <Collapsible /> </div> ); } export default App;

You can also use a collapse plugin, The Inline fold VSCode extension.

Benefits of Using Tailwind CSS Accordion with React

Combining Tailwind CSS with React to create accordion offers a range of benefits that can significantly enhance the development process and user experience. Here are some key advantages:

  • Efficient Development Process: Tailwind CSS provides a utility-first approach to styling, enabling developers (quickly) apply styles using classes. This efficiency is particularly valuable when building complex UI components like accordion. It reduces the time spent writing and managing custom styles, allowing you to focus on functionality and interactivity.

  • Modularity and Reusability: React’s component-based architecture promotes modularity and reusability. You can encapsulate accordion functionality in a single component and reuse it throughout your application. This modular approach simplifies maintenance and update, as changes to the accordion container propagate consistently.

  • Responsive Design: Tailwind CSS offers responsive design utilities that make it straightforward to adapt accordion to different screen sizes and devices. React’s flexibility allows you to conditionally render components based on screen width, ensuring that your accordion is responsive and user-friendly across various platforms.

  • Customization: Tailwind CSS allows for easy customization. You can customize colors, fonts, spacing, and more by modifying the Tailwind CSS configuration, ensuring it aligns with your project’s design and branding requirements.

  • Performance Optimization: It generates optimized and minimal CSS, reducing the size of your stylesheets. This lightweight styling approach, combined with React’s efficient virtual DOM rendering, contributes to faster page load times and smoother interactions.

  • Community and Ecosystem: Both React and Tailwind CSS have large and active communities, which means you have access to a wealth of resources, libraries, and third-party components. This ecosystem provides solutions for challenges and accelerates development.

Best Practices and Tips

Working with Tailwind CSS accordions in React involves combining the utility-first approach of Tailwind CSS with React’s component-based structure. Here are some best practices and tips to help you create efficient and maintainable accordion components:

  • Component-Based Approach: Use React to create reusable and self-contained accordion components. Each accordion-item should be a separate React component.

  • Conditional Rendering: Use conditional rendering to display or hide the content of an accordion item based on its open/closed state.

  • Accessibility: Use semantic HTML elements like buttons or links for accordion headers and provide appropriate ARIA attributes for screen readers. Test your accordion with accessibility tools to ensure it can be navigated and understood by all users.

  • Responsive Design: Use Tailwind CSS’s responsive classes. You can adjust the number of columns or styling based on screen sizes using classes like lg:hidden or md:flex.

  • Documentation: Document your accordion component. If it’s intended for reuse across different projects or by other team members. Provide clear instructions on how to use the accordion component, including the props it accepts and any customization options.

  • Code Organization: Organize your code in a modular and maintainable way. Consider creating separate files for each accordion component, and use a folder structure that makes it easy to find and manage your components.

  • Performance: Optimize the performance of your accordion. If it contains more items, consider techniques like lazy loading content or virtualization to improve rendering speed.

These best practices and tips will help you create well-structured, accessible, and visually appealing Tailwind CSS accordion components in your React applications. It will enhance the user experience and make your codebase more maintainable and adaptable to future changes.

Conclusion

What a long ride!

In conclusion, building accordion in React combines the best of both worlds: the utility-first styling of Tailwind and the component-driven architecture of React. This combination empowers you to create interactive, responsive, and customizable accordion components that enhance user experience.

By following best practices, structuring your code components effectively, and leveraging the flexibility of Tailwind, you can create sleek and efficient accordions that fit seamlessly into your web applications.

So go ahead and implement accordions in your projects, organize your content efficiently, and provide users with a clean and user-friendly interface. With the knowledge and techniques you’ve gained from this guide, you’re well-equipped to create impressive accordion components in React with Tailwind CSS.

Get started with purecode.ai today and ship code faster with PureCode’s AI-powered custom component code generator.

Happy coding!

Phil Butler

Phil Butler