|
| 1 | +import { |
| 2 | + Children, |
| 3 | + cloneElement, |
| 4 | + FC, |
| 5 | + isValidElement, |
| 6 | + ReactNode, |
| 7 | + useCallback, |
| 8 | + useEffect, |
| 9 | + useRef, |
| 10 | + useState, |
| 11 | +} from 'react' |
| 12 | + |
| 13 | +import { AccordionItemProps } from './accordion-item' |
| 14 | +import styles from './Accordion.module.scss' |
| 15 | + |
| 16 | +interface AccordionProps { |
| 17 | + children: JSX.Element[] | JSX.Element |
| 18 | + defaultOpen?: boolean |
| 19 | +} |
| 20 | + |
| 21 | +function computeOpenSectionsState(props: AccordionProps): {[key: string]: boolean} { |
| 22 | + const newOpenState: {[key: string]: boolean} = {} |
| 23 | + |
| 24 | + Children.forEach<ReactNode>(props.children, child => { |
| 25 | + if (!isValidElement(child)) { |
| 26 | + return |
| 27 | + } |
| 28 | + |
| 29 | + const childKey = child.key as string |
| 30 | + newOpenState[childKey] = child.props.open ?? props.defaultOpen |
| 31 | + }) |
| 32 | + |
| 33 | + return newOpenState |
| 34 | +} |
| 35 | + |
| 36 | +const Accordion: FC<AccordionProps> = props => { |
| 37 | + const prevProps = useRef({ ...props }) |
| 38 | + const [openedSections, setOpenedSections] = useState<{[key: string]: boolean}>({}) |
| 39 | + |
| 40 | + const handleToggle = useCallback((key: string) => { |
| 41 | + setOpenedSections(all => ({ ...all, [key]: !all[key] })) |
| 42 | + }, []) |
| 43 | + |
| 44 | + // check if props have changed and update the openedSections synchronously |
| 45 | + if (prevProps.current.defaultOpen !== props.defaultOpen) { |
| 46 | + prevProps.current = { ...props } |
| 47 | + Object.assign(openedSections, computeOpenSectionsState(props)) |
| 48 | + } |
| 49 | + |
| 50 | + // use an effect to make sure the changes are propagated in the state |
| 51 | + useEffect(() => { |
| 52 | + setOpenedSections(computeOpenSectionsState(props)) |
| 53 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 54 | + }, [props.defaultOpen]) |
| 55 | + |
| 56 | + const renderAccordions = (children: JSX.Element[] | JSX.Element): ReactNode => ( |
| 57 | + Children.map<ReactNode, ReactNode>(children, child => { |
| 58 | + if (isValidElement(child)) { |
| 59 | + const childKey = child.key as string |
| 60 | + openedSections[childKey] = openedSections[childKey] ?? child.props.open ?? props.defaultOpen |
| 61 | + |
| 62 | + return cloneElement( |
| 63 | + child, |
| 64 | + { |
| 65 | + open: !!openedSections[childKey], |
| 66 | + toggle: function toggle() { handleToggle(childKey) }, |
| 67 | + } as AccordionItemProps, |
| 68 | + ) |
| 69 | + } |
| 70 | + |
| 71 | + return child |
| 72 | + }) |
| 73 | + ) |
| 74 | + |
| 75 | + return ( |
| 76 | + <div className={styles.wrap}> |
| 77 | + {renderAccordions(props.children)} |
| 78 | + </div> |
| 79 | + ) |
| 80 | +} |
| 81 | + |
| 82 | +export default Accordion |
0 commit comments