import React, { useRef, useEffect, Children, ReactElement, PropsWithChildren, useState, cloneElement } from "react" import s from './AccountNavigation.module.scss' import AccountNavigationItem from './components/AccountNavigationItem/AccountNavigationItem' import {TabPaneProps} from '../../../common/TabCommon/components/TabPane/TabPane' import { ACCOUNT_TAB, QUERY_KEY } from "src/utils/constanst.utils" import { useRouter } from "next/router" interface AccountNavigationProps { defaultActiveIndex: number; children: React.ReactNode } const getTabIndex = (tab?: string): number => { switch (tab) { case ACCOUNT_TAB.CUSTOMER_INFO: return 0; case ACCOUNT_TAB.ORDER: return 1; case ACCOUNT_TAB.FAVOURITE: return 2; default: return 0 } } const AccountNavigation = ({ defaultActiveIndex, children } : AccountNavigationProps) => { const router = useRouter() const [active, setActive] = useState(defaultActiveIndex) const sliderRef = useRef(null); const headerRef = useRef(null) useEffect(() => { const query = router.query[QUERY_KEY.TAB] as string const index = getTabIndex(query) setActive(index) }, [router.query[QUERY_KEY.TAB]]) const onTabClick = (index: number) => { setActive(index) } function slide(index: number) { const active = headerRef.current?.children.item(index)?.getBoundingClientRect() const header = headerRef.current?.getBoundingClientRect() const firstEl = headerRef.current?.children.item(0)?.getBoundingClientRect() const current = sliderRef.current if (current && active && header && firstEl) { const firstElTop = firstEl.top const top = active.top - firstElTop; current.style.top = top.toString()+"px"; } } useEffect(() => { slide(active); }, [active]) return (
    { Children.map(children, (tab, index) => { let item = tab as ReactElement> return (
  • {item.props.tabName}
  • ) }) }
{ Children.map(children, (tab, index) => { let item = tab as ReactElement> return cloneElement(item, { active: index === active }); }) }
) } export default AccountNavigation