NavLink component in React-Router-DOM not accepting style prop with function

Viewed 569

On the React Router Dom page for V5 (https://v5.reactrouter.com/web/api/NavLink/style-object-func) it states that the style prop will accept a function or an object.

When I try to pass the style function listed in the docs I get the following console error:

Failed prop type: Invalid prop style of type function supplied to NavLink, expected object

I am using version 5.2.1 of React Router Dom, and checking the github page for V5 of React Router, it seems the PropTypes are correctly listed (https://github.com/remix-run/react-router/blob/v5/packages/react-router-dom/modules/NavLink.js)

Here is my code:

<NavLink  
  to={"/"}
  style={isActive => ({
    color: isActive ? "green" : "blue"
  })}
>
  {"hello"}
</NavLink>
1 Answers

Seems it may be a bug in v5.2.x of react-router-dom and earlier. Using v5.3.0 (latest) doesn't appear to have this issue. A quick search of the react-router-dom github issues didn't turn anything up though.

Example:

import { BrowserRouter as Router, NavLink } from "react-router-dom";

export default function App() {
  return (
    <Router>
      <div className="App">
        <ul>
          <li>
            <NavLink
              exact
              to={"/"}
              style={(isActive) => ({
                color: isActive ? "green" : "blue"
              })}
            >
              Home
            </NavLink>
          </li>
          <li>
            <NavLink
              exact
              to={"/test"}
              style={(isActive) => ({
                color: isActive ? "green" : "blue"
              })}
            >
              Test
            </NavLink>
          </li>
        </ul>
      </div>
    </Router>
  );
}

Edit navlink-component-in-react-router-dom-not-accepting-style-prop-with-function

What does still work in v5.2.1 is the activeStyle prop.

<NavLink
  exact
  to={"/"}
  style={{ color: "green" }}
  activeStyle={{ color: "blue" }}
>
  Home
</NavLink>

Edit navlink-component-in-react-router-dom-not-accepting-style-prop-with-function (forked)

Related