From 7a9638b88ad7e2ff50c5bf526b818bbcfc112341 Mon Sep 17 00:00:00 2001 From: ameerul-deriv Date: Mon, 30 Sep 2024 10:23:43 +0800 Subject: [PATCH] chore: add scroll to accordion functionality and added ref to accordion --- src/components/Accordion/Accordion.scss | 2 +- src/components/Accordion/index.tsx | 144 +++++++++++++----------- 2 files changed, 82 insertions(+), 64 deletions(-) diff --git a/src/components/Accordion/Accordion.scss b/src/components/Accordion/Accordion.scss index bbc43a55..a773f91f 100644 --- a/src/components/Accordion/Accordion.scss +++ b/src/components/Accordion/Accordion.scss @@ -66,7 +66,7 @@ $animation-duration: 0.3s; } &__content { width: 100%; - overflow: auto; + overflow: scroll; opacity: 0; background-color: var(--content-bg-color); transition: all $animation-duration ease; diff --git a/src/components/Accordion/index.tsx b/src/components/Accordion/index.tsx index 8d92b7a0..63e7e7b4 100644 --- a/src/components/Accordion/index.tsx +++ b/src/components/Accordion/index.tsx @@ -4,6 +4,7 @@ import React, { ReactNode, useEffect, ComponentProps, + forwardRef, } from "react"; import Chevron from "./Chevron.svg"; import clsx from "clsx"; @@ -15,6 +16,7 @@ type AccordionProps = Omit, "title"> & { children: ReactNode; defaultOpen?: boolean; isCompact?: boolean; + onScrollToAccordion?: () => void; title: string | JSX.Element; variant?: AccordionVariants; headerClassName?: string; @@ -27,80 +29,96 @@ const AccordionVariant = { underline: "deriv-accordion--underline", } as const; -export const Accordion = ({ - defaultOpen = false, - children, - isCompact = false, - title, - variant = "underline", - className, - headerClassName, - contentClassName, - ...props -}: AccordionProps) => { - const [active, setActive] = useState(defaultOpen); - const [setHeight, setHeightState] = useState(defaultOpen ? "auto" : "0px"); +export const Accordion = forwardRef( + ( + { + defaultOpen = false, + children, + isCompact = false, + onScrollToAccordion, + title, + variant = "underline", + className, + headerClassName, + contentClassName, + ...props + }, + ref, + ) => { + const [active, setActive] = useState(defaultOpen); + const [heightState, setHeightState] = useState( + defaultOpen ? "auto" : "0px", + ); - const content = useRef(null); + const content = useRef(null); - useEffect(() => { - const scrollHeight = content?.current?.scrollHeight; - setHeightState(active ? `${scrollHeight}px` : "0px"); - }, [active]); + useEffect(() => { + const scrollHeight = content?.current?.scrollHeight; + setHeightState(active ? `${scrollHeight}px` : "0px"); + }, [active]); - const toggleAccordion = () => setActive(!active); + const toggleAccordion = () => { + const newActiveState = !active; + setActive(newActiveState); + setTimeout(() => { + if (onScrollToAccordion && newActiveState) + onScrollToAccordion(); + }, 200); + }; - return ( -
- + return (
+
- {children} +
+ {children} +
-
- ); -}; + ); + }, +);