Advanced React Patterns

Big Head
  • 👀 View the deployed code on Github.
  • Not happy with the solution? 🐞🐛 Suggest a change.
  • Grammar errors? ✏️ Edit this page.

Flexible Compound Components

Summary: create an accordion component (with subcomponents) that has a great API / syntax. The component styles should be fully customizable by those who'll use them.

Create flexible compound components for an "accordion functionality". You should be able to use the components like this:

For simplicity, do not allow any other component as a direct child of the Accord component other than AccordItem. Return an error if that happens. AccordItem must have AccordBtn and AccordPanel as its decendant, but they don't have to be direct descendants. Either you have AccordBtn or both AccordBtnOpen and AccordBtnClose inside AccordItem

You should be able to use this accordion and customize how it looks as you can see in the demonstration of this app.

My Solution

FIXME: This accordion implementation does not follow all best accessibility practices. It should be motified according to the specifications, read more at w3.org

Here are all the accordion related subcomponents:

  • AccordItem
  • AccordPanel
  • AccordBtnOpen
  • AccordBtnClose
  • AccordBtn

Here's the top level Accord component

Here's another bare minimum example usage of the component

Here's a stylized version of the above example

Here's a cool way you can use the components, somewhat different than usual.

Inspired by:

  • Kent C Dodd's Simply React Talk / Repo
  • React UI accordion