161 words
1 minute
Get active link with React Router 4

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 /posts/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!

Get active link with React Router 4
https://edwardbeazer.com/posts/get-active-link-with-react-router-4/
Author
Edward Beazer
Published at
2018-09-05