Developing an Accessible Accordion from Scratch using React

Screenshot of custom accordion

In this article, I want to discuss some of the challenges of building an accessible accordion from scratch using React.

Why Build from Scratch?

If you’re a web developer, you probably know there are plenty of ways you can bring in an accordion. For example, a quick search of ‘react accordion’ on npm will return hundreds of results.

Undoubtedly, there are a lot of helpful options out there for UI. It would be far easier to bring in premade examples than to build something new. Even so, building things from scratch is the perfect way to learn React. It helps:

  • Put some of what you learn from tutorials into practice.
  • Get hands-on experience with website accessibility.

Requirements for Component

The first step was to create a few requirements. These included:

  • Making sure the first tab is open by default.
  • Having only one tab open at a time.
  • Using JSON (JavaScript Object Notation) for the content.
  • Ensuring the accordion worked with the keyboard.
  • Using the correct ARIA (Accessible Rich Internet Applications) Attributes.

For anyone raising an eyebrow at some of the above terms, let me break it down further:

The first two points are just my preference and can be easily changed.

The third point is because many full-stack applications involve working with JSON.

The last two points are two with accessibility standards in web development.

Building an Accessible Accordion

Based on experience, I knew that modern website needed to be less mouse oriented. Instead, they also needed to work with the keyboard to make them more accessible. However, I was by no means an expert on the subject.

I discovered that W3 (World Wide Web Consortium) provide guidelines for many common UI components. Moreover, W3 provides live examples, which makes their instructions easy to follow.

It was easy to use the keyboard with the accordion. To my surprise, I didn’t have to do anything special with keyboard events.

The ARIA Attributes were easy enough to implement using ternary expressions:

aria-expanded={ active === index ? 'true' : 'false' } // returns true dependent on state

Thoughts on Accessibility and Further Homework

In my experience, accessibility is an important but overlooked factor in web development. Furthermore, accessibility also encompasses things like font size, colour contrast ratio and voice recognition. As a developer, it’s a good idea to keep in mind the audience and know some of these key points.

Levelling up this component might include:

  • Integrating with a full-stack app.
  • Using synthetic events to add more keyboard controls.

Check out the link to the accordion here. The code is on my GitHub. Finally, feel free to drop me a line for any accessibility questions.