Last active
February 17, 2020 10:54
-
-
Save isabellachen/9dfb805a62df0af43690f3ea94919ba4 to your computer and use it in GitHub Desktop.
Nested Menu with React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useCallback, useMemo } from 'react'; | |
import { useTranslation } from 'react-i18next'; | |
import { NavLink } from 'react-router-dom'; | |
import { MenuLink } from '~/core/configuration/menu'; | |
type AsideLinkProps = { | |
onClick?: (event: React.MouseEvent<HTMLElement>) => void; | |
children?: JSX.Element[] | null; | |
} & MenuLink; | |
export function AsideLink(props: AsideLinkProps) { | |
const { label, icon, directTo = '', onClick, isOpen = false, isActive = false, nested, children } = props; | |
const [t] = useTranslation(); | |
const navClassNames = useMemo(() => `aside-menu__${nested ? 'menu' : 'list'} ${isActive ? 'is-selected' : ''}`, [ | |
nested, | |
isActive, | |
]); | |
const isOpenClassName = useMemo(() => (isOpen ? 'is-open' : ''), [isOpen]); | |
const onClickLink = useCallback( | |
(e: React.MouseEvent<HTMLElement>) => { | |
if (!directTo) { | |
e.preventDefault(); | |
} | |
if (onClick) { | |
onClick(e); | |
} | |
}, | |
[directTo], | |
); | |
function renderChevron(): JSX.Element | null { | |
return nested && nested.length > 0 ? ( | |
<span className={`aside-menu__list__icon--chevron icon-ic-chevron-right-small ${isOpenClassName}`} /> | |
) : null; | |
} | |
function renderNested(): JSX.Element | null { | |
return nested && nested.length > 0 ? ( | |
<div className={`aside-menu__options ${isOpenClassName}`}>{children}</div> | |
) : null; | |
} | |
return ( | |
<> | |
<NavLink to={directTo} onClick={onClickLink} className={navClassNames}> | |
<div className="aside-menu__list__icon"> | |
<span className={icon} /> | |
{renderChevron()} | |
</div> | |
<p className="aside-menu__list__label">{t(`menu.${label}`)}</p> | |
</NavLink> | |
{renderNested()} | |
</> | |
); | |
} |
Author
isabellachen
commented
Feb 17, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment