Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing isActive on NavLink in React Router with TypeScript

I’m using react-router-dom@6.42 and have the following react component:

import { Link as NavLink } from "react-router-dom";

interface SidebarNavItemProps {
  name: string;
  path: string;
  icon: JSX.Element;
}

const SidebarNavItem = (props: SidebarNavItemProps) => {
  const navLinkCssClasses = ({isActive }): string => {
    return `flex group-hover:text-primary-700 group-hover:bg-primary-50 text-gray-700 font-semibold text-base px-3 py-2 rounded-md ${
      isActive ? "text-primary-700 bg-primary-50" : ""
    }`;
  };

  return (
    <li className="group mb-1">
      <NavLink className={navLinkCssClasses} to={props.path}>
        {props.icon}
        {props.name}
      </NavLink>
    </li>
  );
};

export default SidebarNavItem;

I am using TypeScript and the compiler is not happy. I’m getting two errors:

TS7031: Binding element ‘isActive’ implicitly has an ‘any’ type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TS2322: Type ‘({ isActive }: { isActive: any; }) => string’ is not assignable to type ‘string’.

I tried changing className={navLinkCssClasses} to className={navLinkCssClasses({isActive})} but that still did not help. What am I missing?

>Solution :

the isActive prop is only available for NavLink component. In your code, Link is imported as NavLink. What you have to do is import NavLink itself.

import { NavLink } from "react-router-dom";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading