Today, I want to share how to build an FAQ accordion using react. The FAQ section it's a really important section of an app or a website, since you have an opportunity to have important questions and answers about your product or even your industry and rank better organically in Google.
I hope I'm able to help anyone who wants or needs to build an FAQ section for their website or their app.
I'm leaving the URL of the code and styles at the end of the article and also a working demo if you want to check it out.
We will use 3 different hooks. useState, useRef and useEffect Hooks.
First, we will use the useState hook to change the state of the accordion, like so.
Then, we will use the useRef hook that allow us to mutate the useRef object.
Finally, we will use the useEffect hook to determine the height of the accordion dynamically once the user clicks on the accordion
const [active, setActive] = useState(false);
const contentRef = useRef(null);
useEffect(() => {
contentRef.current.style.maxHeight = active
? `${contentRef.current.scrollHeight}px`
: "0px";
}, [contentRef, active]);
const toggleAccordion = () => {
setActive(!active);
};
Then we have the JSX part of the code using an onClick and ternary operators, like so
return (
<>
<div className="App">
<div>
<button
className={`question-section ${active}`}
onClick={toggleAccordion}
>
<div>
<div className="question-align">
<h4 className="question-style">
Why do you like web developemnt
</h4>
<FiPlus
className={active ? `question-icon rotate` : `question-icon`}
/>
</div>
<div
ref={contentRef}
className={active ? `answer answer-divider` : `answer`}
>
<p>Because I love coding</p>
</div>
</div>
</button>
</div>
</div>
</>
);
I hope you can find this short tutorial helpful, remember that here you have the url of the code and styles if you want to check it out.
Code: https://codesandbox.io/s/infallible-cloud-wiy4y?file=/src/App.js:465-1258
Demo: https://wiy4y.csb.app/
Follow me on Github & Connect with me on LinkedIn
https://github.com/cesareuseche
https://www.linkedin.com/in/cesar-useche-profile/
Top comments (8)
Thanks for this tutorial! Thereโs also the < details > element of you want to save yourself some effort!
developer.mozilla.org/en-US/docs/W...
Thanks, very helpful
Thanks for that info! I'm glad my short tutorial was helpful.
Thanks for this article
I'm glad I was able to help :)
Assuming you have multiple questions, how will you implement it?
Hello! I was wondering how you would be able to set up multiple buttons for multiple questions and answers, thanks!
same here:)