In my recent job switch, the interviewer asked me to create an Accordion Component. This is one of the most basic Machine coding questions that you might face in your interviews.
Understanding the Accordion Component:
At its core, an accordion component is a collapsible container that reveals its content upon user interaction, typically a click. This dynamic behaviour enables users to focus on relevant information while keeping the interface clutter-free.
Implementing Accordion in React:
In this article, we’ll explore how to leverage the power of React to create customizable accordion components. Let’s dive into the code to understand how it works:
// App.js
import React from "react";
import "./App.css";
import Accordion from "./Accordion";
const App = () => {
const accordionData = [
{ content: "My first accordion content", header: "1st accordion header" },
{ content: "My second accordion content", header: "2nd accordion header" },
{ content: "My third accordion content", header: "3rd accordion header" },
];
return (
<div className="font-color">
{accordionData.map((data, index) => (
<Accordion key={index} content={data.content} header={data.header} />
))}
</div>
);
};
export default App;
Let’s create the main task of the article, below is how we can create an Accordion component.
// Accordion.js
import React, { useState } from "react";
function Accordion({ content, header }) {
const [expanded, setExpanded] = useState(false);
const toggleAccordion = () => {
setExpanded(!expanded);
};
return (
<div className="accordion">
<div className="accordion-header" onClick={toggleAccordion}>
<h2>{header}</h2>
<span>{expanded ? "-" : "+"}</span>
</div>
{expanded && (
<div className="accordion-content">
<p>{content}</p>
</div>
)}
</div>
);
}
export default Accordion;
Styling for Enhanced User Experience:
To enhance the user experience, we can apply CSS styles to our accordion component. Here’s a sample CSS code to style the accordion:
/* App.css */
.font-color {
color: #333;
}
/* Accordion.css */
.accordion {
border: 1px solid #ccc;
margin-bottom: 10px;
}
.accordion-header {
background-color: #f4f4f4;
padding: 10px;
cursor: pointer;
display: flex;
justify-content: space-between;
}
.accordion-content {
background-color: #fff;
padding: 10px;
}
With these styles applied, our accordion components will have a clean and modern appearance, ensuring a pleasant user experience.