From 92170958484ae24107c8f6eac8aab24c8cf7b811 Mon Sep 17 00:00:00 2001 From: Aleksandar Ristic Date: Tue, 26 Mar 2024 10:40:51 +0100 Subject: [PATCH] feat: add autoClose prop to accordion --- src/core/Accordion/component.tsx | 34 +++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/core/Accordion/component.tsx b/src/core/Accordion/component.tsx index 0fae6e64..fa6e4f66 100644 --- a/src/core/Accordion/component.tsx +++ b/src/core/Accordion/component.tsx @@ -12,19 +12,19 @@ type AccordionRowProps = { active: boolean; last: boolean; name: string; - index: number; + index; children: ReactNode; arrowIcon: boolean; - activeIndex: number; setActiveIndex: (index: number) => void; }; -type AccordionProps = { +export type AccordionProps = { data: AccordionData[]; arrowIcon: boolean; topBorder: boolean; bottomBorder: boolean; id: string; + autoClose?: boolean; }; const AccordionRow = ({ @@ -40,11 +40,7 @@ const AccordionRow = ({ }: AccordionRowProps) => { let iconActive: JSX.Element, iconInactive: JSX.Element; const handleSetIndex = () => { - if (active) { - setActiveIndex(null); - } else { - setActiveIndex(index); - } + setActiveIndex(index); }; if (arrowIcon) { @@ -107,8 +103,23 @@ const Accordion = ({ topBorder, bottomBorder, arrowIcon, + autoClose, }: AccordionProps) => { - const [activeIndex, setActiveIndex] = useState(null); + const [activeIndexes, setActiveIndexes] = useState([]); + + const handleSetIndex = (index: number) => { + const currentIndexIsActive = activeIndexes.includes(index); + + if (autoClose) { + setActiveIndexes(currentIndexIsActive ? [] : [index]); + } else { + setActiveIndexes( + currentIndexIsActive + ? activeIndexes.filter((i) => i !== index) + : [...activeIndexes, index] + ); + } + }; return (
@@ -119,12 +130,11 @@ const Accordion = ({ name={item.name} arrowIcon={arrowIcon} index={currentIndex} - activeIndex={activeIndex} last={data.length === currentIndex + 1} topBorder={topBorder && currentIndex === 0} bottomBorder={bottomBorder && data.length === currentIndex + 1} - active={activeIndex === currentIndex} - setActiveIndex={setActiveIndex} + active={activeIndexes.includes(currentIndex)} + setActiveIndex={handleSetIndex} > {item.content}