coding dentist
coding dentist

Reputation: 93

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

Upvotes: 9

Views: 17275

Answers (3)

Zaykahal
Zaykahal

Reputation: 92

"activeClassName" is no longer a property of NavLink. Instead you can use either style or className to apply your "isActive".

more on their official documentations: https://reactrouter.com/en/6.14.2/upgrading/v5#remove-activeclassname-and-activestyle-props-from-navlink-

Upvotes: 4

Joel Ambu
Joel Ambu

Reputation: 115

style can either be a React.CSSProperties object or a function that returns a style object. If the function style is used, the link’s active state is passed as a parameter. doc

<NavLink
      to="/faq"
         style={isActive => ({
         color: isActive ? "green" : "blue"
      })}
    >
    FAQs
  </NavLink>

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202686

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>

Upvotes: 10

Related Questions