Kartik Budhraja
Posted on September 30, 2023
Introduction
In modern web design, user interaction is paramount. Accordion components, those neat expandable and collapsible sections, are widely used to optimize space and enhance user experience. In this tutorial, we'll guide you through the process of creating a responsive accordion component in React. We'll break down the code step by step, explaining the logic behind each section. Let's dive in!
So let's get started.
Initial Project Setup
Create a new project using create-react-app
npx create-react-app your-component-app
Setting the Foundation: Import Statements
To start, let's import the necessary modules and components. We bring in the Accordion component from a separate file and a local stylesheet (styles.css). Additionally, we import React and its powerful useState hook, a fundamental part of React's functional components.
import Accordion from "./Accordion";
import "./styles.css";
import React, { useState } from "react";
Defining the Data Structure
Accordions often display dynamic content. In our example, we define an array of objects named AccordionMenu. Each object represents an accordion item with properties like index, title, and content. This data will be dynamically rendered by our React components.
const AccordionMenu = [
{
index: 0,
title: "Content 1",
content: `Aperiam ab atque incidunt dolores ullam est, earum ipsa recusandae velit cumque. Aperiam ab atque incidunt dolores ullam est, earum ipsa recusandae velit cumque.`
},
{
index: 1,
title: "Content 2",
content: `Sapiente expedita hic obcaecati, laboriosam similique omnis architecto ducimus magnam accusantium corrupti
quam sint dolore pariatur perspiciatis, necessitatibus rem vel dignissimos
dolor ut sequi minus iste? Quas?`
},
{
index: 3,
title: "Content 3",
content: `Lorem ipsum, dolor sit amet consectetur adipisicing elit. Mollitia veniam
reprehenderit nam assumenda voluptatem ut. Ipsum eius dicta, officiis
quaerat iure quos dolorum accusantium ducimus in illum vero commodi
pariatur? Impedit autem esse nostrum quasi, fugiat a aut error cumque
quidem maiores doloremque est numquam praesentium eos voluptatem amet!
Repudiandae, mollitia id reprehenderit a ab odit!`
}
];
Building the Functional Component: App
The core of our application is the App functional component. Here, we employ React's useState hook to manage the active index of the accordion. The handleAccordionClick function toggles the active index, ensuring that only one accordion item is open at any given time. This component maps through the AccordionMenu array, rendering individual Accordion components with appropriate props.
export default function App() {
const [activeIndex, setActiveIndex] = useState(-1);
const handleAccordionClick = (index) => {
setActiveIndex(index === activeIndex ? -1 : index);
};
return (
<div className="App">
<h1>Accordion</h1>
<div className="accordion">
{AccordionMenu.map((item, index) => (
<Accordion
key={index}
title={item.title}
content={item.content}
index={index}
activeIndex={activeIndex}
onAccordionClick={handleAccordionClick}
/>
))}
</div>
</div>
);
}
Constructing the Accordion Component
The Accordion component is where the magic happens. It receives various props like title, content, index, activeIndex, and onAccordionClick. Based on these props, it determines whether the current accordion item should be active or not. When a user clicks on an accordion title, the onAccordionClick function is triggered, updating the active index and re-rendering the component accordingly.
const Accordion = ({ title, content, index, activeIndex, onAccordionClick }) => {
const isActive = index === activeIndex;
return (
<div className="accordion-item" key={title}>
<div className="accordion-title" onClick={() => onAccordionClick(index)}>
<div>{title}</div>
<div>{isActive ? "-" : "+"}</div>
</div>
{isActive && <div className="accordion-content">{content}</div>}
</div>
);
};
Polishing with CSS
To make our accordions visually appealing and responsive, we apply CSS styles. Specific styles are defined for the accordion container, individual accordion items, titles, and content. Media queries ensure the accordions adapt gracefully to various screen sizes, providing a seamless user experience.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 20px;
background: rgb(94, 89, 91);
background: radial-gradient(
circle,
rgb(255, 247, 250) 0%,
rgb(174, 179, 180) 100%
);
}
h1 {
text-align: center;
margin: 2rem 0 4rem 0;
}
.accordion {
max-width: 600px;
margin: 2rem auto;
}
.accordion-item {
margin-bottom: 12px;
}
.accordion-title {
display: flex;
flex-direction: row;
justify-content: space-between;
cursor: pointer;
background-color: #21aeca;
}
.accordion-title:hover {
background-color: #12759c;
}
.accordion-title,
.accordion-content {
padding: 1rem;
}
.accordion-content {
background-color: #39b9d275;
}
@media screen and (max-width: 700px) {
body {
font-size: 18px;
}
.accordion {
width: 90%;
}
}
Conclusion
In conclusion, building a responsive accordion component in React involves careful management of state and props. By organizing the code into modular components and applying CSS styles for a polished look, we can create a user-friendly accordion interface. Understanding the interplay between React components and their states is crucial in developing interactive web applications. By following this step-by-step guide, developers can create similar components, enhancing their skills in React development and user interface design. Happy coding!
Follow Me on Social Media!
If you found this article helpful, feel free to connect with me on LinkedIn and Twitter for more programming tips and tutorials. Let's learn and grow together!
LinkedIn: https://www.linkedin.com/in/kartikbudhraja/
Twitter: https://twitter.com/K_a_r_t_i_k_08
Posted on September 30, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.