Author -  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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY