0

I am new to react.js. I am unable to get params from the current URL.

Here is the function I use:

var Base_URL = window.location.href;

Now I want to parse the params of current URL that looks like this: url=xyz&email=xyz. How can I achieve this with React. I perfectly get all values while using node.js.

Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30
  • 1
    `const params = new URLSearchParams(window.location.search)` - then you can do e.g. `for (const [key, value] of params.entries()) console.log(\`${key} = ${value}\`)` or `console.log(params.get('email'))`. See docs for [`Location`](https://developer.mozilla.org/en-US/docs/Web/API/Location) and [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). – CherryDT Jul 27 '23 at 12:17

1 Answers1

0

You could use the react-router-dom package's useLocation hook.

    const function useSearchQuery() {
      const { search } = useLocation();
      return useMemo(() => new URLSearchParams(search), [search]);
    }

Then call the function and get the params you want

    const query = useSearchQuery();
    email = query.get('email')