Search code examples
reactjsreact-router-dom

why activeClassName property in NavLink is not working in 6.0.2 version of react router?


I was using the activeClassName property to add a new class to the link when it is in active state.it worked well in version 5.0.3 of react-router-dom . but in version 6.0.2 it started showing me warning and its not working. I couldn't able to find any descriptions about this change in the documents given in react-router website .

 <NavLink
    className={classes.registerButton}
    activeClassName={classes.active}
    to="/auth/SignUp"
  >cart</NavLink>

image of the warning which was shown in the developer console


Solution

  • The NavLink API changed a bit in RRDv6, there is no longer an activeClassName prop.

    NavLink

    interface NavLinkProps
      extends Omit<LinkProps, "className" | "style"> {
      caseSensitive?: boolean;
      className?:
        | string
        | ((props: { isActive: boolean }) => string);
      end?: boolean;
      style?:
        | React.CSSProperties
        | ((props: {
            isActive: boolean;
          }) => React.CSSProperties);
    }
    

    You can conditionally apply your active class via a className prop function.

    <NavLink
      className={({ isActive }) => {
        const linkClasses = [classes.registerButton];
        if (isActive) linkClasses.push(classes.active);
        
        return linkClasses.join(" "); // returns "registerButton" or "registerButton active"
      }}
      to="/auth/SignUp"
    >
      cart
    </NavLink>