ActiveLink Refactor with TypeScript
ActiveLink.js
1import { withRouter } from 'next/router';
2import Link from 'next/link';
3import React, { Children } from 'react';
4
5const ActiveLink = ({ router, children, ...props }) => {
6 const child = Children.only(children);
7
8 let className = child.props.className || '';
9 if (router.pathname === props.href && props.activeClassName) {
10 className = `${className} ${props.activeClassName}`.trim();
11 }
12
13delete props.activeClassName;
14
15return <Link {...props}>{React.cloneElement(child, { className })}</Link>;
16};
17
18export default withRouter(ActiveLink);
ActiveLink.tsx
1import { withRouter, NextRouter } from 'next/router';
2import React, { ReactElement } from 'react';
3import Link from 'next/link';
4
5type Props = {
6 router: NextRouter;
7 children: ReactElement;
8 href: string;
9 activeClassName: string;
10}
11
12const ActiveLink = ({ router, children, ...props }: Props) => {
13
14 let className: string = children.props.className;
15 if (router.asPath === props.href) {
16 className = `${className} ${props.activeClassName}`;
17 }
18
19 return (
20 <Link {...props}>{React.cloneElement(children, { className })}</Link>
21 );
22}
23
24export default withRouter(ActiveLink);