Home > Mobile >  NavLink className isActive arg from react-router v6 does not work
NavLink className isActive arg from react-router v6 does not work

Time:11-16

Brief summary of what my problem is with react-router-dom NavLink component:

  • style with the function inside using isActive works just fine

  • className with the function inside using isActive does not work at all

    • in this case i can write anything inside that function, console.log does not get written to console and the active NavLink gets one class: active; the others get no class at all

style={({ isActive }) => ({ backgroundColor: isActive? 'red' : 'blue' })} // This works

className={({ isActive }) => isActive? 'custom-active-class' : 'custom-other-class' } // This DOES NOT work

In the className case the NavLinks get the following classlists:

  • my active NavLink gets a classlist of just one element: "active"
  • my passive NavLinks does not get any classes

If i write just some simple console.logs inside these functions the following happens:

style={({ isActive }) => console.log('STYLE')} // This works

className={({ isActive }) => console.log('CLASSNAME')} // This DOES NOT work

The component should look like this

<NavLink
    to="random-url"
    style={({ isActive }) => ({ backgroundColor: isActive? 'red' : 'blue' })} // This works
    className={({ isActive }) => isActive? 'custom-active-class' : 'custom-other-class' } // This DOES NOT work
>
    My NavLink
</NavLink>

This is what is seen in the elements tab after setting className with isActive: enter image description here

And my dependencies:

  • react-router-dom: ^6.4.3
  • react: ^17.0.1
  • react-dom: ^17.0.1

Sadly i cannot give a reproducible example, i tried it on Codesandbox with the same versions and packages i have but the same thing works fine there. Does anybody have an idea how to make this work?

CodePudding user response:

Because instead of setting a className, your'e setting an object like { backgroundColor: 'custom-active-class'} as the className value, you should set the className to 'custom-active-class' instead and then define the styles of that class like this:

.custom-active-class {
   background-color:red;
}
.custom-other-class{
   background-color:blue;
}
 <NavLink
        to="random-url"
        style={({ isActive }) => ({ backgroundColor: isActive? 'red' : 'blue' })} // This works
        className={({ isActive }) =>isActive ? 'custom-active-class' : 'custom-other-class' }
    >
        My NavLink
    </NavLink>

CodePudding user response:

I have create the example of NavLink in react-rout-dom 6.4.3 It is working fine.

  1. Please use this link. It will help you. https://codesandbox.io/s/react-fiddle-forked-r072u0?file=/src/App.js:0-498
  • Related