How to Make an Accordion using React

accordion

Introduction

Accordions are a popular user interface pattern that allows users to toggle the display of content in a collapsible manner. In this blog post, we’ll explore the implementation of a responsive and stylish accordion component using React. The provided React code, combined with CSS styles, creates an interactive accordion that is both visually appealing and functional.

Understanding the React Accordion Component

The provided React code defines a functional component named Accordion. Let’s break down its structure and functionality.

import React, { useState } from "react";
import "./accordion.css"; // Import your updated stylesheet

const Accordion = () => {
  const [activeIndex, setActiveIndex] = useState(null);

  const handleToggle = (index) => {
    setActiveIndex((prevIndex) => (prevIndex === index ? null : index));
  };

  let content = [
    "Who is Viral Coder",
    "Lorem Ipsum is Lorem Ipsum",
    "Coding Good News article",
  ];

  return (
    <div className="container">
      {content.map((item, index) => (
        <div className="wrapper" key={index}>
          <button
            className="toggle"
            onClick={() => handleToggle(index)}
            style={{
              color: activeIndex === index ? "#3498db" : "#2c3e50",
            }}
          >
            {item}
            {index === activeIndex ? (
              <>
                <i className="fas fa-minus icon"></i>
              </>
            ) : (
              <>
                <i className="fas fa-plus icon"></i>
              </>
            )}
          </button>
          <div
            className="content"
            style={{
              maxHeight: activeIndex === index ? "1000px" : "0px",
            }}
          >
            <p>
              {index === 0
                ? "Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta aliquam facere adipisci quod mollitia, aut nemo deleniti fugiat et, corrupti sequi. Omnis dolorem quos eligendi placeat soluta sint corrupti quod."
                : index === 1
                ? "Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores error doloremque, quibusdam qui necessitatibus autem aperiam reprehenderit? Ipsum maiores dolore inventore ea. Accusantium fuga eius laboriosam iusto blanditiis doloremque ullam?"
                : "Lorem ipsum dolor sit amet consectetur adipisicing elit. Recusandae consectetur officiis labore commodi sunt ex praesentium dolor magnam asperiores reiciendis. Minus magnam nesciunt aliquid eos ipsam sequi recusandae quos incidunt."}
            </p>
          </div>
        </div>
      ))}
    </div>
  );
};

export default Accordion;
JSX

Explanation:

  • useState: The useState hook is used to manage the state of the active accordion item index. It returns the current state (activeIndex) and a function (setActiveIndex) to update it.
  • handleToggle Function: This function toggles the active accordion item. If the clicked item is already active, it sets the active index to null (collapses the accordion); otherwise, it sets the active index to the clicked item index.
  • content Array: This array contains the titles for each accordion item. You can customize this array with your own titles.
  • Mapping through Accordion Items: The map function is used to iterate over the content array and render individual accordion items.
  • Button Element (toggle): Each accordion item has a button that triggers the toggle functionality. The button’s color changes based on whether the item is active or not.
  • Toggle Icon: The icon next to the button changes based on the active state. It displays a minus icon when expanded and a plus icon when collapsed.
  • Content Section: The content of each accordion item is wrapped in a div with the class content. This section expands and collapses based on the active state.

Styling the Accordion with CSS

The provided CSS code styles the React accordion component to make it visually appealing and user-friendly.

@import url("https://fonts.googleapis.com/css2?family=Rubik:wght@400;600&display=swap");

*,
*:before,
*:after {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

body {
    background-color: #1e1c27;
    font-family: "Rubik", sans-serif;
}

.container {
    width: 45%;
    min-width: 500px;
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
}

.wrapper {
    background-color: #ecf0f1;
    /* Change the background color */
    margin-bottom: 20px;
    padding: 15px 40px;
    border-radius: 8px;
    /* Make it more unique */
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
    /* Update the box-shadow */
    transition: box-shadow 0.8s ease;
    /* Add transition to box-shadow */
}

.wrapper:hover {
    box-shadow: 0 15px 25px rgba(0, 0, 0, 0.2);
}

.toggle {
    width: 100%;
    background-color: transparent;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    color: #2c3e50;
    /* Change the text color */
    font-weight: 500;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 15px 0;
    transition: color 0.8s ease;
    /* Add transition to text color */
}

.toggle:hover {
    color: #3498db;
    /* Change the text color on hover */
}

.content {
    position: relative;
    font-size: 14px;
    text-align: justify;
    line-height: 30px;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.8s ease;
    /* Add transition to max-height */
}
CSS

Explanation:

  • container: Styles for the overall container of the accordion.
  • wrapper: Styles for each accordion item, including background color, padding, border radius, and box shadow. Hover effects are added to enhance interactivity.
  • toggle: Styles for the toggle button, including width, background color, font size, color, padding, and cursor. The button color changes on hover.
  • content: Styles for the content section, including positioning, font size, text alignment, line height, maximum height (for animation), overflow, and transition for smooth expansion and collapse.

Conclusion

In this blog post, we’ve dissected the React code for an accordion component and explored how to style it using CSS. The resulting accordion is not only functional but also visually appealing, making it a great addition to your web development projects. Feel free to customize the content, styles, and icons to match your specific requirements.

Integrate this accordion into your React applications and provide users with a seamless and interactive way to explore content.

Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *