Building an accordion in React

·

2 min read

The accordion can be really useful and are commonly seen in sections like FAQs and menus. There may be various ways to implement one but the main idea is to enable opening and closing functionality to a component where a section expands and closes.

accordiondemo_.gif

This is one way to implement a basic accordion in React. For my example, I am using Tailwind.

First make sure we import useState at the top of the file and set the state.

const [open, setOpen] = useState(false)

Set up a button (it doesn't have to be a button element) - when the user clicks on it, the state should be set to Open. For this, we have to create a function which we can call openToggle(). If the value of 'open' is false, we want to set it to true, and if true, to false.

function openToggle() {
    setOpen(!open)
  }

Now we can give the button an onClick handler to call the function.

<button onClick={() => openToggle()}>Click</button>

For the button, any kind of indication to visually represent the opened and closed state would be helpful, and in my case I used an svg of a '+' sign that rotates to an 'x'. I have a conditional attribute in the class (using React). If using Tailwind, this is easy to do: className={${open ? 'rotate-0' : 'rotate-45' }}

In default state: Screen Shot 2022-11-01 at 7.23.01 PM.png

In opened state: Screen Shot 2022-11-01 at 7.22.50 PM.png

We can make a container div to hold the content and this container will have a height of auto and another conditional class, such as 'item-open' . In the css, set up certain attributes for this open class including "height: 100%". In this way, section is zero height at default, and when it is expanded it becomes 100%.

<div className={`w-full ${ open ? 'item-open h-auto' : 'h-auto' }`}>
"Content goes here"
</div>

The content can be imported as data or hard-coded. This example is for one tab or section of the accordion, so in this way it can be used as a reusable component for as many tabs as needed.

Thank you for reading!