import { useState, FC } from 'react'; import AccordionItem, { AccordionItemProps } from './AccordionItem'; export type AccordionItem = Omit; export interface AccordionProps { /** * The index of the item that should be open by default. * @default -1 */ indexOpen?: number; /** An array of items to display in the accordion. */ items: readonly AccordionItem[]; /** A callback function that is called when an item is clicked. */ onClick?: (index: number) => void; /** * @deprecated * @default 'light' */ theme?: 'light' | 'dark'; } /** * Accordion * * A simple accordion component that displays a list of items that can be expanded or collapsed. * * @component * @param {number} indexOpen - index of the item that should be open * @param {Array} items - array of items to display * @param {Function} onClick - callback function * @example * // Example usage: * * import Accordion from './Accordion'; * * const items = [ * { * id: 'item1', * title: 'Item 1', * content: 'This is the content for item 1.', * }, * { * id: 'item2', * title: 'Item 2', * content: 'This is the content for item 2.', * }, * { * id: 'item3', * title: 'Item 3', * content: 'This is the content for item 3.', * }, * ]; * * function App() { * const handleItemClick = (index) => { * console.log(`Item ${index} was clicked.`); * }; * * return ( * * ); * } */ const Accordion: FC = ({ indexOpen = -1, items, onClick, theme = 'light' }) => { const [itemsOpen, setItemsOpen] = useState(() => items.map((value, index) => index === indexOpen), ); /** * Handles a click event on an accordion item. * * @param index The index of the item that was clicked. */ const handleOnClick = (index: number) => { if (onClick) { onClick(index); } const newItems = [...itemsOpen]; newItems[index] = !itemsOpen[index]; setItemsOpen(newItems); }; return ( <> {items.map((item, index) => ( handleOnClick(index)} /> ))} ); }; export default Accordion;