Categories
React Answers

How to set activeClassName for wrapper element of Link or IndexLink in React Router?

Spread the love

Sometimes, we want to set activeClassName for wrapper element of Link or IndexLink in React Router.

In this article, we’ll look at how to set activeClassName for wrapper element of Link or IndexLink in React Router.

How to set activeClassName for wrapper element of Link or IndexLink in React Router?

To set activeClassName for wrapper element of Link or IndexLink in React Router, we can set the className prop of our wrapper element.

For instance, we write

import React, { PropTypes } from "react";
import { Route, Link } from "react-router-dom";
import styles from "./styles.less";

export default function NavItem({ children, to, exact }) {
  return (
    <Route
      path={to}
      exact={exact}
      children={({ match }) => (
        <li className={match ? styles.activeRoute : null}>
          <Link to={to}>{children}</Link>
        </li>
      )}
    />
  );
}

to set the li‘s className prop to the class we want.

And we wrap that around the Link so the li will be rendered as the parent of the anchor rendered by the Link.

Conclusion

To set activeClassName for wrapper element of Link or IndexLink in React Router, we can set the className prop of our wrapper element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *