This article demonstrates building a dynamic accordion component using React.js. It's a user-friendly, space-saving UI element ideal for web and mobile apps.
Prerequisites:
Project Setup:
npx create-react-app accordion-component
/accordion-component/
folder contains all the necessary files.Project Structure and Initial Setup:
/accordion-component/
folder in your code editor.npm run start
(from the terminal)./src/AccordionComponent/
folder. Inside, create Accordion.js
(for the component) and AccordionData.js
(for data storage).App.js
, import and render Accordion.js
:import './App.css'; import Accordion from './AccordionComponent/Accordion'; function App() { return ( <div className="App"> <Accordion /> </div> ); } export default App;
App.css
and index.css
.Accordion Component Structure:
Accordion.js
, create the AccordionItem
component:import React from 'react'; const AccordionItem = () => { return (<h1>Accordion</h1>); }; const Accordion = () => { return ( <div> <AccordionItem /> </div> ); }; export default Accordion;
AccordionData.js
:const data = [ { question: 'What are accordion components?', answer: '...' }, { question: 'What are they used for?', answer: '...' }, // ... more questions and answers ]; export default data;
(Replace ...
with your actual question and answer text.)
Component Layout and Styling:
react-icons
: npm install react-icons
useState
, useRef
, and RiArrowDropDownLine
in Accordion.js
:import React, { useRef, useState } from 'react'; import { RiArrowDropDownLine } from 'react-icons/ri';
AccordionItem
component:const AccordionItem = ({ question, answer, isOpen, onClick }) => { const contentHeight = useRef(); return ( <div className="wrapper"> <div className={`question-container ${isOpen ? 'active' : ''}`} onClick={onClick}> <p className="question-content">{question}</p> <RiArrowDropDownLine className={`arrow ${isOpen ? 'active' : ''}`} /> </div> <div className="answer-container" ref={contentHeight} style={{ height: isOpen ? contentHeight.current.scrollHeight : "0px" }}> <p className="answer-content">{answer}</p> </div> </div> ); };
Add CSS styling (in a new Accordion.css
file or within App.css
): (The provided CSS is extensive; consider breaking it into smaller, more manageable stylesheets).
Implement the main Accordion
component:
import './App.css'; import Accordion from './AccordionComponent/Accordion'; function App() { return ( <div className="App"> <Accordion /> </div> ); } export default App;
Remember to import data
from AccordionData.js
and link the CSS file. This detailed breakdown provides a clearer path to building the accordion component. The original response's code blocks were very long and difficult to follow. This revised answer breaks it down into smaller, more manageable chunks.
The above is the detailed content of How to Build an Accordion Component with React.js. For more information, please follow other related articles on the PHP Chinese website!