Getting value dynamically from URL React.js

Viewed 32

I have a problem where I need to get some value from URL however I need to get this value in the first component to be rendered so this component is not inside any Route or something and I guess in this way I am not able to use useParams hook.

const bookSlug = location.pathname.split('/')[3];

I am getting the value from url like this right now and I don't think that this is a good way. Is there any other way?

1 Answers

Getting path:

in this case we use useLocation and location object is returned to us

{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere',
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}

Getting query string properties:

in this case we use useParams. this hook returns an object of key/value pairs of URL parameters.

I your case useLocation would do your job.

Related