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.
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.
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.
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.
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>
);
}