October Sunday,31st 2021: AM

ActiveLink Refactor with TypeScript

ActiveLink.js

import { withRouter } from 'next/router';
import Link from 'next/link';
import React, { Children } from 'react';

const ActiveLink = ({ router, children, ...props }) => {
  const child = Children.only(children);

  let className = child.props.className || '';
  if (router.pathname === props.href && props.activeClassName) {
    className = `${className} ${props.activeClassName}`.trim();
  }

delete props.activeClassName;

return <Link {...props}>{React.cloneElement(child, { className })}</Link>;
};

export default withRouter(ActiveLink);

ActiveLink.tsx

import { withRouter, NextRouter  } from 'next/router';
import React, { ReactElement } from 'react';
import Link from 'next/link';

type Props = {
  router: NextRouter;
  children: ReactElement;
  href: string;
  activeClassName: string;
}

const ActiveLink = ({ router, children, ...props }: Props) => {

  let className: string = children.props.className;
  if (router.asPath === props.href) {
    className = `${className} ${props.activeClassName}`;
  }

  return (
    <Link {...props}>{React.cloneElement(children, { className })}</Link>
  );
}

export default withRouter(ActiveLink);