How to use query parameters in react router
In this tutorial, we are going to learn about how to use and access the query parameters from a URL in react router.
Query parameters
Query parameters are added to the end of a URL with a question mark followed by the key-value pairs (?key=value) by using that we can filter the data.
localhost:8080/users?name=sai
// In this url key is name and value is sai
Passing query params
We can pass query params to the Link
component like this.
<Link to={{pathname:"/users",search: "?name=sai"}}>Sai</Link>
or
<Link to="/users/?name=sai">Sai</Link>
Accessing query params
To access the query params from a url, we need to use the react router useLocation hook.
import React from 'react';
import {useLocation} from "react-router-dom";
function Users() {
const location = useLocation();
console.log(location);
return (
<div>
<h1>Users page</h1>
<p>{new URLSearchParams(location.search).get('name')}</p> </div>
);
}
In class-based components, we can access the query params using this.props.location
object.
import React from 'react';
class Users extends React.Component{
render(){
const search = this.props.location.search;
return <p>{new URLSearchParams(location.search).get('name')}</p> }
}
Note: React Router does not have any built-in methods to parse your URL query strings so that in the above examples we have used the
URLSearchParams
interface.