--- title: Accordion tags: components,children,state,advanced firstSeen: 2019-03-02T10:46:34+02:00 lastUpdated: 2021-01-07T23:57:13+02:00 --- Renders an accordion menu with multiple collapsible content elements. - Define an `AccordionItem` component, that renders a `
{children}
); }; const Accordion = ({ defaultIndex, onItemClick, children }) => { const [bindIndex, setBindIndex] = React.useState(defaultIndex); const changeItem = itemIndex => { if (typeof onItemClick === 'function') onItemClick(itemIndex); if (itemIndex !== bindIndex) setBindIndex(itemIndex); }; const items = children.filter(item => item.type.name === 'AccordionItem'); return ( <> {items.map(({ props }) => ( changeItem(props.index)} children={props.children} /> ))} ); }; ``` ```jsx ReactDOM.render( Lorem ipsum Dolor sit amet , document.getElementById('root') ); ```