Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking router.isActive on nested Routes in React

I'm trying to check routes with Router.isActive

If the current route is /animals/edit

(router.isActive('/animals/edit')

is true.

But if the current route is /animals/edit/23

(router.isActive('/animals/edit/') 

is false.

How can I make a route that encompasses trailing params?

like image 214
lost9123193 Avatar asked May 03 '17 02:05

lost9123193


2 Answers

I had the same issue. Solved it by matching the route using router.getCurrentLocation().pathname.

In your example, the following should do it:

const parentPathname = '/animals/edit';
const currentPathname = router.getCurrentLocation().pathname;
const isActive = currentPathname.indexOf(parentPathname) !== -1;
like image 56
Regn Avatar answered Sep 28 '22 07:09

Regn


Unfortunately I don't think this is possible with router.isActive as it doesn't support path params (i.e. router.isActive('/animals/edit/:number')).

As an alternative, using React Router v4's matchPath you could do:

import { matchPath } from 'react-router'

const match = matchPath(currentPath, {
  path: '/animals/edit(/:number)',
  exact: true,
  strict: false
})
like image 34
crosscompile Avatar answered Sep 28 '22 09:09

crosscompile