How can I use react hooks and get query string value?
with react class I use :
const id = this.props.match.params.id;
How can I use react hooks and get query string value?
with react class I use :
const id = this.props.match.params.id;
import { useParams } from "react-router-dom";
in component:
const { id } = useParams();
URLSearchParams()
and useLocation()
react hook , like const queryP =new URLSearchParams(useLocation().search)
see specs for URLSearchParams –
Expressage 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
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
useLocation().search
is equivalent to window.location.search
, right ?! –
Latarsha 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()
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]);
};
© 2022 - 2024 — McMap. All rights reserved.