How to show different icon in active NavLink in react-router-dom v6?

Viewed 258

I want to show a different icon when a particular nav link is active.

I made a new component

import React, { useState } from "react";
import { NavLink } from "react-router-dom";

const CustomNavLink = ({ to, activeIcon, inActiveIcon }) => {
  const [isActive, setIsActive] = useState(false);
  const changeActive = ({ isActive }) => setIsActive(isActive);
  return (
    <NavLink to={to} className={changeActive}>
      {isActive ? activeIcon : inActiveIcon}
    </NavLink>
  );
};

export default CustomNavLink;

enter image description here But When I am using this code it is giving me this error. How to solve this error?

1 Answers

The NavLink already has its own internal isActive state, there's no need to duplicate that. The className prop should return a string type or undefined. Use the children prop function instead of trying to enqueue state updates during the render.

Example:

import React, { useState } from "react";
import { NavLink } from "react-router-dom";

const CustomNavLink = ({ to, activeIcon, inActiveIcon }) => {
  return (
    <NavLink
      to={to}
      children={({ isActive }) => isActive ? activeIcon : inActiveIcon}
    />
  );
};

export default CustomNavLink;

or

const CustomNavLink = ({ to, activeIcon, inActiveIcon }) => {
  return (
    <NavLink to={to}>
      {({ isActive }) => isActive ? activeIcon : inActiveIcon}
    </NavLink>
  );
};
Related