Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if react-router path is active

How to check if generic react-router path matches current location pathname?

react-router path: /Movies/:id
location.pathname: /Movies/56fa7446bae6eb301e5937f3

I want to use route paths with menu buttons, to set class="active".

EDIT:

To clarify, paths in my app look like:

/Movies/56fa7/watch

and not like:

/Movies/watch/56fa7

How do I check if the former route is active?

Is it doable without <Link> component?

/Movies/56fa7/watch is arbitrary after /Movies, and <Link> obviously can't be pointed to an arbitrary location. So let's ignore <Link> for a moment:

Is there a standalone function or property in react-router that checks if /Movies/:id/watch is active?

like image 341
Luka Avatar asked Mar 29 '16 16:03

Luka


2 Answers

According to the docs, you could use matchPath function which takes two arguments:

  1. pathname you want to match (String).
  2. options (Object) or path (String) to match against.

If matched it will return an object of this shape:

{
  path, // the path used to match
  url, // the matched portion of the URL
  isExact, // whether or not we matched exactly
  params
}

Otherwise you'll get null.

To make use of it in your components you could simply do:

import { matchPath } from 'react-router';

// ...

render () {
  const isMovieWatchPathActive = !!matchPath(
    this.props.location.pathname, 
    '/Movies/:id/watch'
  ); 

  // ...
}

Hope it'll help someone.

like image 91
streletss Avatar answered Nov 09 '22 00:11

streletss


As of React Router v4 (March 2017):

I'm a bit late to the party, but hopefully this will help anyone with the same question. When a component is rendered through a Route, certain props are passed to it. These props can be used to determine which route is active.

In a component rendered by a Route, you can use this.props.match.url to get the actual URL requested by the browser, and you can use this.props.match.path to get the path pattern for the current route.

Check working example here: https://codesandbox.io/s/20o7q0483j

Docs related to this are available here: https://reacttraining.com/react-router/web/api/Route/Route-props

like image 5
Shishir Avatar answered Nov 09 '22 02:11

Shishir