3

If you have URLs in your app that can change (e.g /profile/1 and /profile/2, how do you access that from this.props.location.pathname?

In my Profile component I have a componentDidMount method like so:

componentDidMount () {
    if (this.props.location.pathname === 'profile/:id/') {
      console.log('is profile')
  } else {
      console.log('is not profile')
  }
}

Which returns is not profile when I'm on the profile pages.

The project I'm using uses react-redux-starter-kit as a base (not sure if that helps), which uses react-router-v3.

0

5 Answers 5

3

You can try this

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

if (matchPath(this.props.location.pathname, { path: 'profile/:id' })) {}

Or

this.props.match.path === 'profile/:id'

I'm not sure why your Profile component gets mounted if it's not a profile though.

Sign up to request clarification or add additional context in comments.

Comments

3

if (this.props.location.pathname === 'profile/:id/')

this will never be true because of :id is a matcher:

try:

if (this.props.match.params.id)

This way you will check if there's id parameter in current route.

https://jaketrent.com/post/access-route-params-react-router-v4/

3 Comments

Sorry Tomasz, should've clarified I'm using react-router ^3.0.0
@A7DC I think it's the same.
Thanks Tomasz, didn't work for me but lead me in the right direction
2

With React hooks you can do something like this

import {Route, useRouteMatch} from 'react-router-dom'

const App = () => {
    const match = useRouteMatch("match/this/route/:id")
    return (
        //suppose you dont want to show navbar in this route
        {match && match.path === 'match/this/route/:id' ? <SomeComponent/> : <Navbar/>}
    )}
//match.path check for the dynamic route match/this/route/:id

Comments

1

This doesn't feel like the best way to do this, but it worked for me:

this.props.location.pathname === '/profile/' + this.props.params.id

Comments

0

use match props to get dynamic path

componentDidMount () {
  if (this.props.match.path === 'profile/:id') {
    console.log('is profile')
  } else {
    console.log('is not profile')
  }
}

refer this for more information react-redux-match

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.