How to get query params of a current URL in React

#react #react-router-dom

Last updated on Oct 3, 2020 by Suraj Sharma



In this tutorial, you will learn how you can extract query params of the current URL using react-router-dom v5.1


Consider, you have a <Link /> in our React App


<Link to="/home?library=react&lang=javascript">Home</Link>


First, To get the current URL you can use useLocation() hook available in the react-router-dom


const location = useLocation();


Now we are going to separate the query params from the current URL using the JavaScript URLSearchParams interface.

To do this we are going to create a custom React hook useQueryParams()


const useQueryParams = () => {
 const location = useLocation();
 return new URLSearchParams(location.search);
}


This returns a URLSearchParams object instance.


We can use the URLSearchParams get() method to retrieve the search parameters value inside the <Home /> component


const Home = () => {
  const queryParams = useQueryParams();

  return (
    <p>{`Library is ${queryParams.get('library')}`}</p>
    <p>{`Language is ${queryParams.get('lang')}`}</p>
  );
}


Related Articles



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.