user4200410
user4200410

Reputation:

React Router NavLink does not render activeClassName when mapped

The activeClassName of React Routers NavLink does not work when mapped as shown in the following code. The view receives the links from its container as props where they are mapped. Everything works well, including the standard className, but the activeClassName doesn´t work. It works when I add a NavLink manually outside the mapping but I cant find the mistake. Any help appreciated.

import React from "react";
import { NavLink } from "react-router-dom";
import styles from './style.scss';

class NavView extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
      return (
          <ul>
            {this.props.links.map(function(link, index) {
              return <li key={index}> <NavLink to={link.slug} className="navLink" activeClassName="current" >{link.slug}</NavLink></li>
            })}
          </ul>
      );
  }
}
export default NavView

Upvotes: 2

Views: 3000

Answers (1)

jered
jered

Reputation: 11571

I'm quite certain that you simply need to add a / slash to the beginning of your routes' link slugs.

import React from "react";
import { NavLink } from "react-router-dom";
import styles from './style.scss';

class NavView extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
      return (
          <ul>
            {this.props.links.map(function(link, index) {
              return <li key={index}> <NavLink to={`/${link.slug}`} className="navLink" activeClassName="current" >{link.slug}</NavLink></li>
            })}
          </ul>
      );
  }
}
export default NavView;

React-router is quite specific and picky about matching URL patterns. If your route is /home, <NavLink/> will only match when the to prop is also /home, not home.

Upvotes: 3

Related Questions