Skip to main content

Getting Started

Install

npm install @szhsin/react-accordion

Usage

An accordion is created by wrapping any number of AccordionItem components inside an Accordion component.

By default, only one accordion item can be expanded at one time.

tip

When focus is on an accordion header, you may use the ArrowDown and ArrowUp keys to move focus to the next or previous accordion header.

import { Accordion, AccordionItem } from '@szhsin/react-accordion';

export default function Example() {
return (
<Accordion>
<AccordionItem header="What is Lorem Ipsum?">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</AccordionItem>

<AccordionItem header="Where does it come from?">
Quisque eget luctus mi, vehicula mollis lorem. Proin fringilla
vel erat quis sodales. Nam ex enim, eleifend venenatis lectus
vitae, accumsan auctor mi.
</AccordionItem>

<AccordionItem header="Why do we use it?">
Suspendisse massa risus, pretium id interdum in, dictum sit amet
ante. Fusce vulputate purus sed tempus feugiat.
</AccordionItem>
</Accordion>
);
}

Try on CodeSandbox

Or, if your data is already in an array:

import { Accordion, AccordionItem } from '@szhsin/react-accordion';

const items = [
{
header: 'What is Lorem Ipsum?',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing...'
},
{
header: 'Where does it come from?',
content: 'Quisque eget luctus mi, vehicula mollis lorem...'
},
{
header: 'Why do we use it?',
content: 'Suspendisse massa risus, pretium id interdum in...'
}
];

export default function Example() {
return (
<Accordion>
{items.map(({ header, content }, i) => (
<AccordionItem header={header} key={i}>
{content}
</AccordionItem>
))}
</Accordion>
);
}
info

Although the header prop of AccordionItem looks like some simple text content, you may provide it with any JSX elements or React components, allowing the item header to be freely customised.

Accessibility

This library implements WAI-ARIA roles, states, properties, and keyboard interaction, which is compliant with the Accordion Pattern.