DEV Community

Cover image for How to build a React FAQ accordion

Posted on

How to build a React FAQ accordion

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(() => { = active
      ? `${contentRef.current.scrollHeight}px`
      : "0px";
  }, [contentRef, active]);

  const toggleAccordion = () => {
Enter fullscreen mode Exit fullscreen mode

Then we have the JSX part of the code using an onClick and ternary operators, like so

return (
      <div className="App">
            className={`question-section ${active}`}
              <div className="question-align">
                <h4 className="question-style">
                  Why do you like web developemnt
                  className={active ? `question-icon rotate` : `question-icon`}
                className={active ? `answer answer-divider` : `answer`}
                <p>Because I love coding</p>
Enter fullscreen mode Exit fullscreen mode

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.



Follow me on Github & Connect with me on LinkedIn

Top comments (7)

endymion1818 profile image
Ben Read • Edited

Thanks for this tutorial! There’s also the < details > element of you want to save yourself some effort!

dela profile image
Robert Deladem Dakey

Thanks, very helpful

cesareuseche profile image

Thanks for that info! I'm glad my short tutorial was helpful.

alexsvt2 profile image
Alexis López

Thanks for this article

cesareuseche profile image

I'm glad I was able to help :)

skylarrji profile image
Skylar Ji

Hello! I was wondering how you would be able to set up multiple buttons for multiple questions and answers, thanks!

aadilraza339 profile image

same here:)