React Hooks - How to get parameter value from query string
Asked Answered
C

5

31

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

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

Chiliarch answered 17/6, 2020 at 10:36 Comment(0)
A
31
import { useParams } from "react-router-dom";

in component:

const { id } = useParams();

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

Anemone answered 17/6, 2020 at 11:1 Comment(6)
this is terribly wrong , it will never return url query params !Expressage
yep, but his question was about param of react routerSettler
@JimmyObonyoAbor, wonder what is your solution? thanksGorgoneion
@Gorgoneion for query params use combination of URLSearchParams() and useLocation() react hook , like const queryP =new URLSearchParams(useLocation().search) see specs for URLSearchParamsExpressage
Thanks @JimmyObonyoAbor, much better answer, your previous one was little negative :)Gorgoneion
@MiroslavPapírník but the question states "query string", doesn't it?Phenoxide
F
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
Funky answered 11/4, 2021 at 11:38 Comment(0)
I
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

Incoming answered 12/7, 2021 at 6:8 Comment(2)
So basically, useLocation().search is equivalent to window.location.search, right ?!Latarsha
Shouldn't that be the correct answer?Phenoxide
H
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()
Hopping answered 30/3, 2023 at 11:49 Comment(0)
T
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]);
};
Tropic answered 17/6, 2020 at 10:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.