Skip to content

Commit

Permalink
Added a shouldShowActiveForSubroutes option
Browse files Browse the repository at this point in the history
  • Loading branch information
JasonStoltz committed Nov 12, 2020
1 parent b8576ed commit 6581bfa
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,30 @@ describe('SideNavLink', () => {
expect(wrapper.find('.enterpriseSearchNavLinks__item--isActive')).toHaveLength(1);
});

it("won't set an active class when route is a subroute of 'to'", () => {
(useLocation as jest.Mock).mockImplementationOnce(() => ({ pathname: '/documents/1234' }));

const wrapper = shallow(
<SideNavLink to="/documents" isRoot>
Link
</SideNavLink>
);

expect(wrapper.find('.enterpriseSearchNavLinks__item--isActive')).toHaveLength(0);
});

it('sets an active class if the current path is a subRoute of "to", and shouldShowActiveForSubroutes is true', () => {
(useLocation as jest.Mock).mockImplementationOnce(() => ({ pathname: '/documents/1234' }));

const wrapper = shallow(
<SideNavLink to="/documents" isRoot shouldShowActiveForSubroutes>
Link
</SideNavLink>
);

expect(wrapper.find('.enterpriseSearchNavLinks__item--isActive')).toHaveLength(1);
});

it('passes down custom classes and props', () => {
const wrapper = shallow(
<SideNavLink to="/" className="testing" data-test-subj="testing">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,17 @@ export const SideNav: React.FC<SideNavProps> = ({ product, children }) => {

interface SideNavLinkProps {
to: string;
shouldShowActiveForSubroutes?: boolean;
isExternal?: boolean;
className?: string;
isRoot?: boolean;
subNav?: React.ReactNode;
}

export const SideNavLink: React.FC<SideNavLinkProps> = ({
isExternal,
to,
shouldShowActiveForSubroutes = false,
isExternal,
children,
className,
isRoot,
Expand All @@ -82,7 +84,10 @@ export const SideNavLink: React.FC<SideNavLinkProps> = ({

const { pathname } = useLocation();
const currentPath = stripTrailingSlash(pathname);
const isActive = currentPath === to || (isRoot && currentPath === '');
const isActive =
currentPath === to ||
(shouldShowActiveForSubroutes && currentPath.startsWith(to)) ||
(isRoot && currentPath === '');

const classes = classNames('enterpriseSearchNavLinks__item', className, {
'enterpriseSearchNavLinks__item--isActive': !isExternal && isActive, // eslint-disable-line @typescript-eslint/naming-convention
Expand Down

0 comments on commit 6581bfa

Please sign in to comment.