Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add an active class to a Link from React Router?

Tags:

react-router

I've created a bootstrap-style sidebar using Link. Here is a snippet of my code:

<ul className="sidebar-menu">   <li className="header">MAIN NAVIGATION</li>   <li><Link to="dashboard"><i className="fa fa-dashboard"></i> <span>Dashboard</span></Link></li>   <li><Link to="email_lists"><i className="fa fa-envelope-o"></i> <span>Email Lists</span></Link></li>   <li><Link to="billing"><i className="fa fa-credit-card"></i> <span>Buy Verifications</span></Link></li> </ul> 

I want to set the class for the active path to active on the wrapping element <li>. I see there are other solutions out there that show how to do this like Conditionally set active class on menu using react router current route, however I don't think that it's the best way to set an active class on a wrapper to a Link.

I also found https://github.com/insin/react-router-active-component but it feels like it is unnecessary.

In React Router, is this possible or do I need to use an external solution?

like image 212
coderberry Avatar asked Dec 22 '15 14:12

coderberry


People also ask

How do you make a link active in React?

The first method is to use the react-router-dom inbuilt method of NavLink instead of Link. The NavLink supports activeClassName which can help us assign active className to the link.


1 Answers

On the Link component you can now add activeClassName or set activeStyle.

These allow you to easily add styles to the currently active link.


Previously, you could create a custom component that works like a wrapper to Link with the following logic.

In a file called nav_link.js

import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types';  class NavLink extends React.Component {     render() {         var isActive = this.context.router.route.location.pathname === this.props.to;         var className = isActive ? 'active' : '';          return(             <Link className={className} {...this.props}>                 {this.props.children}             </Link>         );     } }  NavLink.contextTypes = {     router: PropTypes.object };  export default NavLink; 

And use it as given below in your component:

... import NavLink from "./nav_link"; .....  <nav>     <ul className="nav nav-pills pull-right">         <NavLink to="/">             <i className="glyphicon glyphicon-home"></i> <span>Home</span>         </NavLink>         <NavLink to="about">             <i className="glyphicon glyphicon-camera"></i> <span>About</span>         </NavLink>     </ul> </nav> 
like image 119
Vijey Avatar answered Sep 21 '22 02:09

Vijey