6

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?

Tim Foley
  • 665
  • 1
  • 5
  • 6
lost9123193
  • 10,460
  • 26
  • 73
  • 113

2 Answers2

2

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;
Regn
  • 281
  • 2
  • 4
1

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
})