32

How can I use react hooks and get query string value?

with react class I use : const id = this.props.match.params.id;

5 Answers 5

30
import { useParams } from "react-router-dom";

in component:

const { id } = useParams();

https://reactrouter.com/en/main/hooks/use-params

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

6 Comments

this is terribly wrong , it will never return url query params !
yep, but his question was about param of react router
@JimmyObonyoAbor, wonder what is your solution? thanks
@smile for query params use combination of URLSearchParams() and useLocation() react hook , like const queryP =new URLSearchParams(useLocation().search) see specs for URLSearchParams
Thanks @JimmyObonyoAbor, much better answer, your previous one was little negative :)
|
27

here is another pure javascript way

assuming your URL = localhost:3000/example?id=123

  React.useEffect(() => {

    const params = new URLSearchParams(window.location.search) // id=123
    let id = params.get('id') // 123 

}, [])

you can also check if the query params exist or not by has like

params.has('id') // true
params.has('name') // false

Comments

12

In React Hooks:

Suppose your URL is like this: http://localhost:3000/user?name=John&id=10

Then you can use useLocation hook to get your job done.

import React from 'react';
import { useLocation } from "react-router-dom";

function VerifySignup() {
    const search = useLocation().search;
    const name = new URLSearchParams(search).get('name');
    const id = new URLSearchParams(search).get('id');
    console.log({ name, id })
    return (
        <div>
            Verify Signup
        </div>
    )
}

export default VerifySignup

2 Comments

So basically, useLocation().search is equivalent to window.location.search, right ?!
Shouldn't that be the correct answer?
5

You can create your own hook

import { useLocation } from "react-router";

export default function useQueryParams() {
    const search = useLocation().search;
    const urlSearchParams = new URLSearchParams(search);
    const params = Object.fromEntries(urlSearchParams.entries());
    return params
}

and then use it in you code like this

import useQueryParams from 'useQueryParams.js'

const { param1, param2 } = useQueryParams()

Comments

1

You can use useParams and set the id as a dependency of the effect:

const Component = () => {
  const { id } = useParams();
  useEffect(() => 'do something when id changes', [id]);
};

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.