by Sai gowtham

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.

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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course