Skip to content

Commit

Permalink
refactor(v2): use Collapsible for mobile nav items
Browse files Browse the repository at this point in the history
  • Loading branch information
lex111 committed Jul 11, 2021
1 parent d7c2df6 commit 2820e4e
Showing 1 changed file with 12 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ import clsx from 'clsx';
import Link from '@docusaurus/Link';
import useBaseUrl from '@docusaurus/useBaseUrl';
import {useLocation} from '@docusaurus/router';
import {isSamePath} from '@docusaurus/theme-common';
import {
isSamePath,
useCollapsible,
Collapsible,
} from '@docusaurus/theme-common';
import type {
NavLinkProps,
DesktopOrMobileNavBarItemProps,
Expand Down Expand Up @@ -167,11 +171,11 @@ function NavItemMobile({
position: _position, // Need to destructure position from props so that it doesn't get passed on.
...props
}: DesktopOrMobileNavBarItemProps) {
const menuListRef = useRef<HTMLUListElement>(null);
const {pathname} = useLocation();
const [collapsed, setCollapsed] = useState(
() => !items?.some((item) => isSamePath(item.to, pathname)) ?? true,
);
const {collapsed, toggleCollapsed} = useCollapsible({
initialState: () =>
!items?.some((item) => isSamePath(item.to, pathname)) ?? true,
});

const navLinkClassNames = (extraClassName?: string, isSubList = false) =>
clsx(
Expand All @@ -190,10 +194,6 @@ function NavItemMobile({
);
}

const menuListHeight = menuListRef.current?.scrollHeight
? `${menuListRef.current?.scrollHeight}px`
: undefined;

return (
<li
className={clsx('menu__list-item', {
Expand All @@ -205,16 +205,11 @@ function NavItemMobile({
{...props}
onClick={(e) => {
e.preventDefault();
setCollapsed((state) => !state);
toggleCollapsed();
}}>
{props.children ?? props.label}
</NavLink>
<ul
className="menu__list"
ref={menuListRef}
style={{
height: !collapsed ? menuListHeight : undefined,
}}>
<Collapsible as="ul" className="menu__list" collapsed={collapsed}>
{items.map(({className: childItemClassName, ...childItemProps}, i) => (
<li className="menu__list-item" key={i}>
<NavLink
Expand All @@ -225,7 +220,7 @@ function NavItemMobile({
/>
</li>
))}
</ul>
</Collapsible>
</li>
);
}
Expand Down

0 comments on commit 2820e4e

Please sign in to comment.