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:
- As @arjun.dev points out, you've imported
Link as NavLinkwhere you should have importedNavLink—React Router'sLinkcomponent doesn't take a function as aclassName, whereNavLinkdoes. - Since
navLinkCssClassesis 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>
);
};
