Home > Enterprise >  react-router v6 history.location.search replacement
react-router v6 history.location.search replacement

Time:08-07

In react-router v5 I was able to use

let keyword = history.location.search

but in react-router v6 I get an error so what is the replacement for that code?

Edit: BTW I am not so good at router and currently converting a code from v5. I was wondering what should keyword return in v5? The path I am currently in?

CodePudding user response:

It's was always the case that you should have accessed the search value from the location object instead of the history object.

See history is mutable

The history object is mutable. Therefore it is recommended to access the location from the render props of <Route>, not from history.location. This ensures your assumptions about React are correct in lifecycle hooks.

If the tutorial is showing using history.location.search I wouldn't give it much weight.

In react-router-dom@6 however, there are no longer any route props, i.e. no history, location, or match props. You instead access these all via React hooks. Note that the history object is also no longer directly exposed out to components, replaced by a navigate function via the useNavigate hook.

To access the queryString RRDv6 introduced a new useSearchParams hook.

Given URL "/somepath?someQueryParam=123"

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

...

const [searchParams, setSearchParams] = useSearchParams();

const someQueryParam = searchParams.get("someQueryParam"); // 123

Additional Question

Edit: Btw I am not so good at router and currently converting a code from v5 I was wondering what should keyword return in v5 ? The path I am currently in?

location.search is a string, so you could process the string manually, or create a URLSearchParams object.

Check the RRDv5 Query Parameters demo

They create a custom useQueryHook:

function useQuery() {
  const { search } = useLocation();

  return React.useMemo(() => new URLSearchParams(search), [search]);
}

then access named query params with the getter:

let query = useQuery();

...

const name = query.get("name");

CodePudding user response:

example url: https://example.com/?foo=bar

import { useSearchParams } from 'react-router-dom'

const Component = () => {
  const [searchParams, setSearchParams] = useSearchParams()
  const foo = searchParams.get('foo')
  console.log(foo) // "bar"
  return <></>
}

Obviously, you need to use this inside a router.

Note: all search param values are strings.

CodePudding user response:

The useHistory-hook from v5 has been replaced in React Router v6 for the useNavigate-hook. This can be checked in the upgrade documentation. For further information on useNavigate just check the docs.

  • Related