UNPKG

@equinor/eds-core-react

Version:

The React implementation of the Equinor Design System

57 lines (54 loc) 1.5 kB
import { forwardRef, useState, Children, cloneElement, useEffect } from 'react'; import { jsx } from 'react/jsx-runtime'; const AccordionItem = /*#__PURE__*/forwardRef(function AccordionItem({ headerLevel, chevronPosition, index = 0, accordionId, isExpanded = false, onExpandedChange, children, disabled, ...props }, ref) { const [expanded, setExpanded] = useState(isExpanded); const controlled = onExpandedChange !== undefined; const activeExpandedState = controlled ? isExpanded : expanded; const toggleExpanded = () => { if (disabled) return; if (controlled) { onExpandedChange?.(!isExpanded); } else { setExpanded(!expanded); } }; const processedChildren = Children.map(children, (child, childIndex) => { const headerId = `${accordionId}-header-${index + 1}`; const panelId = `${accordionId}-panel-${index + 1}`; return childIndex === 0 ? /*#__PURE__*/cloneElement(child, { isExpanded: activeExpandedState, toggleExpanded, id: headerId, panelId, headerLevel, chevronPosition, parentIndex: index, disabled }) : /*#__PURE__*/cloneElement(child, { hidden: !activeExpandedState, id: panelId, headerId }); }); useEffect(() => { if (!controlled) { setExpanded(isExpanded); } }, [isExpanded, controlled]); return /*#__PURE__*/jsx("div", { ...props, ref: ref, children: processedChildren }); }); export { AccordionItem };