How to use query parameters in react router

How to use query parameters in react router

In this post we will give you information about How to use query parameters in react router. Hear we will give you detail about How to use query parameters in react routerAnd how to use it also give you demo for it if it is necessary.

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.

Users.js
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.

Hope this code and post will helped you for implement How to use query parameters in react router. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US