Search code examples
javascriptreactjsreact-router-dom

How to apply correct classname for active NavLink react-router-dom v6?


I try to style my active nav link but I cant do this, the link always has class "flights-table-daylink active-Btn".

This is my code, I watched this in tutorial from good guy but in my project this does not work.

codesandbox.io/s/style-navllink-sksgrg?file=/src/App.js

const setActive = ({ isActive }) =>
  isActive ? "flights-table-daylink active-Btn" : "flights-table-daylink";

<NavLink to="/departure" className={setActive}>
  <span>1</span>
</NavLink>

Solution

  • If you don't provide a to prop to a NavLink component in React Router, it will not be able to determine whether the current route matches the link's destination. The className prop has been set to the setActive function, which will return a different class name based on the isActive property.

    When you provide a to prop to a NavLink, React Router will compare the current URL with the destination URL specified in the to prop. If the current URL matches the to prop of the NavLink, the isActive property will be true, and the active-Btn class will be applied to the NavLink. Otherwise, the isActive property will be false, and only the flights-table-daylink class will be applied.

    const setActive = ({ isActive }) =>
      isActive ? "flights-table-daylink active-Btn" : "flights-table-daylink";
    
     <NavLink to={"/"} className={setActive}>
       <span>1</span>
     </NavLink>
    

    Now everything will work exactly as you expected.