Get active link with React Router 4

Find your active route with this quick and easy method

Wed, 05 Sep 2018

Earlier today I was creating a navbar using react-bootstrap and I was having trouble finding a way to get the current active route. The solution is nice and easy to use. All you need to do is import a class from react-router-dom

import {withRouter} from 'react-router-dom';

When you wrap withRouter around a component it will give you read access to your history and location objects within this.props. Wrapping your component is as simple as this

class Layout extends React.Component {}
export default withRouter(Layout);

Once you wrap your component with withRouter we can look at the location object for our current pathname. This pages exact link is https://edwardbeazer.com/get-active-link-with-react-router-4. Using the key pathname, this.props.location.pathname will result in the following string - /get-active-link-with-react-router-4. So in my example where I was creating a nav, if I wanted to reference the exact location I would write something similar to

if (this.props.location.pathname ===/get-active-link-with-react-router-4) {
 // do some stuff
}

As for the nav, super simple once you implement this method!

Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge