UNPKG

react-handy-hooks

Version:
99 lines (83 loc) 2.52 kB
--- name: useAccordion menu: hooks --- # useAccordion useAccordion is a react hook that returns two prop getters, `getHeaderProps` and `getSectionProps`, and an `isActiveSection` function, which allow you to build the tabs component you want without forgetting about accessibility. ### **getHeaderProps** It's a function that takes in a unique id and index, and returns all the props that should be applied to each tab header. Here is the list of returned props: - aria-controls - aria-disabled - aria-expanded - id - key - onClick - onFocus - onKeyDown - ref If you spread these props over a custom component, make sure to properly pass down ref (typically, using `React.forwardRef`). ### **getSectionProps** It's a function that takes in a unique id and index, and returns all the props that should be applied to each tab header. Here is the list of returned props: - aria-hidden - aria-labelledby - id - key - role - style - ref If you spread these props over a custom component, make sure to properly pass down ref (typically, using `React.forwardRef`). ### **isActiveSection** It's a simple function that takes in an index of the tab header/section and returns true or false depending whether it's an active one or not. import { Playground } from 'docz'; import { useAccordion } from '../'; ## Example <Playground> {() => { const AccordionHeader = React.forwardRef((props, ref) => ( <button {...props} style={{ fontSize: '16px' }}> {props.isOpen ? 'close' : 'open'} </button> )); const AccordionSection = React.forwardRef((props, ref) => ( <div {...props}> <div ref={ref}>{props.children}</div> </div> )); const Example = () => { const { getHeaderProps, getSectionProps, isActiveSection, } = useAccordion(); const items = [ { id: 'one', section: 'section one', }, { id: 'two', section: 'section two', }, ]; return ( <div aria-label="accordion example"> {items.map(({ id, section }, index) => ( <div key={id}> <AccordionHeader isOpen={isActiveSection(index)} {...getHeaderProps(id, index)} /> <AccordionSection {...getSectionProps(id, index)}> {section} </AccordionSection> </div> ))} </div> ); }; return <Example />; }} </Playground>