React Router Dom: Parsing Query String Parameters

Updated: March 3, 2023 By: A Goodman Post a comment

If your React web application uses React Router for navigation and routing, you use the useLocation hook to get the location object that represents the current URL. Once you have the location object, you can retrieve and parse the query string like this:

 const location = useLocation();
 const queryString = location.search;

 const params = new URLSearchParams(queryString);
 console.log(params.get('key'));

For more clarity, see the complete example below.

Note: This tutorial uses the latest version of React Router (6.x). Make sure you don’t use older versions like 5.x or 4.x.

Example

Preview:

The complete code:

// App.js
// Kindacode.com
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useLocation,
} from 'react-router-dom';

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path='/' element={<HomePage />} />
      </Routes>
    </Router>
  );
};

// Home Page
const HomePage = (props) => {
  const location = useLocation();
  const search = location.search;
  console.log(search);

  const params = new URLSearchParams(search);
  console.log(params.get('s'));

  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        flexDirection: 'column',
        marginTop: 100,
      }}
    >
      <h3>S: {params.get('s')}</h3>
      <h3>Page: {params.get('page')}</h3>
      <h3>Limit: {params.get('limit')}</h3>
      <h3>Sort: {params.get('sort')}</h3>
      <h3>Order: {params.get('order')}</h3>
    </div>
  );
};

export default App;

Run your project and go to:

http://localhost:3000/?s=foo&page=1&limit=10&sort=date&order=desc

Then check the output.

What’s Next?

If you’d like to learn more about modern React and React Native, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles