Home > Software engineering >  Accessing isActive on NavLink in React Router with TypeScript
Accessing isActive on NavLink in React Router with TypeScript

Time:10-11

I'm using [email protected] 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.

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?

CodePudding user response:

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";

CodePudding user response:

You've got two issues here, which should be easy to fix:

  1. As @arjun.dev points out, you've imported Link as NavLink where you should have imported NavLink—React Router's Link component doesn't take a function as a className, where NavLink does.
  2. Since navLinkCssClasses is a function, its parameters (isActive) must be typed correctly
// this is important
import { NavLink } from "react-router-dom";

/* ... */

const SidebarNavItem = (props: SidebarNavItemProps) => {
  // make sure to type the parameters of this function! isActive is a boolean 
  const navLinkCssClasses = ({ isActive }: { isActive: boolean }): 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>
  );
};

  • Related