by Sai gowtham

How to get the query params in React

In this tutorial, we are going to learn about how to get the query params from a current URL in react using the react-router.

Query params

Query params are passed to the end of a URL using question mark ? followed by the key=value pairs.

Example:

localhost:3000/items?name=pen

To get the query parameter from a above url, we can use the useLocation() hook in react router v5.

Items.js
import React from 'react';
import {useLocation} from "react-router-dom";
export default function Items() {

  const search = useLocation().search;  const name = new URLSearchParams(search).get('name');

  return (
    <div>
      <h1>Items page</h1>
      <p>{name}</p>    </div>
  );
}

In the above code, we first imported the useLocation() hook from the react-router-dom package and invoked it inside the Items functional component then we parsed the query param data using the new URLSearchParams().get() method.

In react router v4, we can access the query param data from a URL using the props.location.search property.

Items.js
import React from 'react';

export default function Items(props) {

  const search = props.location.search;  const name = new URLSearchParams(search).get('name');
  return (
    <div>
      <h1>Items page</h1>
      <p>{name}</p>    </div>
  );
}

In class-based components, you can access it like this.

Items.js
import React, { Component } from "react";

class Items extends Component {
  render() {
    const search = this.props.location.search;    const name = new URLSearchParams(search).get("name");
    return (
      <div>
        <h1>Items page</h1>
        <p>{name}</p>      </div>
    );
  }
}

export default Items;

Multiple Query parameters

If you are passing multiple query parameters to a URL using the & (and) operator.

localhost:3000/items?name=pen&id=12

you can access it like this.

Items.js
import React from 'react';
import {useLocation} from "react-router-dom";

export default function Items() {

  const search = useLocation().search;
  const name = new URLSearchParams(search).get('name');  const id = new URLSearchParams(search).get('id');
  return (
    <div>
      <h1>Items page</h1>
      <p>{id}</p>      <p>{name}</p>    </div>
  );
}

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