In this article, we will learn about Query params in React Router and also we see Search params in React Router. Below you can see complete details about Query Params and Search Params in React Router with examples.

React Router Query Params


In the previous article, we learned about dynamic routes with react-router-dom. we created the user's listing page and nested the user's details page. it's all working great but there is room for improvement.

At the moment we just display the text details about the user, irrespective of who the user is. 

In a typical application, you would want to extract the userId and do something

with that id, perhaps make an API call to fetch the details about that user.

React Router V6 Query Params

For our scenario let's keep it simple and display the user id from the URL in the component.


Now, to extract the route parameter we need to import a hook from the react-router package.


In the user details file at the top import useParams from react-router-dom

import { useParams } from 'react-router-dom'

And then call the hook within the component use params with parentheses, the hook returns an object of key-value pairs. Let's call it params,  so const params are equal to use params, this object contains key-value pairs of the dynamic params from the current URL, the parameter we want to access is user Id.

const params = useParams()

Let's store that in a constant, const user id is equal to params.userId

const userId = params.userId

It is important to note here that userId on the params object, corresponds to the dynamic segment we

have specified in the route config (App.js), colon user Id.

App.js


import { Component } from 'react'
import { Routes, Route } from 'react-router-dom'
import { UserDetails } from './components/UserDetails';
import { Users } from './components/Users';


function App() {
return (
<Routes>
<Route path="users" element={<Users />} >
<Route path=":userId" element={<UserDetails />} />
<Route path="admin" element={<Admin />} />
</Route>

<Route path="*" element={<PageNotFound />} />
</Routes>
);
}

export default App;

Once we have the user id, we can render it as part of JSX details about the user and we render the user Id.

return (
<div>
Details about user {userId}
</div>
)


Here are the complete UserDetails.js file

UserDetails.js

import React from 'react'
import { useParams } from 'react-router-dom'

export const UserDetails = () => {
const params = useParams()
const userId = params.userId
return (
<div>
Details about user {userId}
</div>
)
}

If we now save the file and head back to the browser,  navigate to slash users slash one and we see the text details about user one

http://localhost:3000/users/1

Change the Id  to slash two, we see details about user two

http://localhost:3000/users/2

Change the Id to slash 100, details about user 100.

http://localhost:3000/users/100


So this is pretty much how you get hold of URL params in your component, import the use params hook and invoke it and access the property on the returned object.


React Router V6 Search Params


We learned about dynamic routes and URL params, which represent part of the URL that is
dynamic. We also learned how to extract the dynamic param within a component using the use param hook.

What you should know is that URL params are not the only way to add parameters to a route. We can also add an optional query string
For example at the end of the current URL question mark filter is equal to active

http://localhost:3000/users?filter=active

These parameters are called search params in react-router.

For our understanding, let's implement a simple scenario in the users.js page, let's add two buttons
one that says active users and one that says reset filter.




By default the page renders the text showing all users, on click of active users, we're going to add a search param called filter and set it to active, in the component, we will display text showing active users.

If you click on reset, we remove the filter search param and revert the text.

Now changing the text is pretty simple and your app might have more complex requirements i just want to ensure you understand the concept of search params and how to put it to use is up to you

Let's begin,

Step 1:
In the user's component, let's add two buttons, the first button is active users and the second button is reset filter

<button>Active Users</button>
<button>Reset Filter</button>
Step 2:
 
on click of these buttons, we need to add or remove the search param, to deal with search params react-router provides a hook called use search params.
import { Outlet, useSearchParams } from 'react-router-dom'
this hook behaves similar to the useState hook in react, instead of storing state in memory
though it is stored in the URL.

Within the component invoke the hook use search patterns, the hook returns two values of which the

The first one is an object which we are going to call search patterns and
the second value returned is a function to set the search patterns so let's call this set search patterns

const [searchParams, setSearchParams] = useSearchParams()
as you can see it is very similar to useState

Now using useSearchParams() function we can add or remove the parameter.

First on click of active users button, onCick we're going to have an arrow function, where we call set search params and we pass in an object with one property called filter, this value is active
<button onClick={() => setSearchParams({ filter: 'active' })}>Active Users</button>

Next onClick of reset filter button, we call set search params again but this time with an empty object.

<button onClick={() => setSearchParams({})} >Reset Filter</button>
let's save the file and test if this works, so we are here at localhost 3000 slash users. Click on active users and you can see we have a question mark filter that is equal to active.  Click on reset filter and the search param is removed.

Now what we need to do is check if the filter search param is set to active and display the appropriate text.

Step 3:

Within the component, we make a check on the filter parameter
const show active users and this is going to be a boolean value to get hold of the filter parameter we use the get function on search params, so search params dot get, what is the pattern name that is filter, we then compare the value with the string active.
const showActiveUsers = searchParams.get('filter') === 'active'
Show active users is true if we click on the active user's button and false if we click on the reset filter button

Let's use it to render the JSX curly braces show active users if it is true return an h2 tag that says showing active users and if it is false return an h2 tag that says showing all users.

{
showActiveUsers ? (
<h2>Showing active users</h2>
) : (
<h2>Showing all users</h2>
)
}

For now, take a look at the browser you can see the text showing all users, click on active users we see the search param in the URL and the text is now showing active users, reset filter showing all users once again.

Below is the complete Users.js file
import React from 'react'
import { Outlet, useSearchParams } from 'react-router-dom'
export const Users = () => {
const [searchParams, setSearchParams] = useSearchParams()

const showActiveUsers = searchParams.get('filter') === 'active'
return (
<div>
<h2> User 1</h2>
<h2> User 2</h2>
<h2> User 3</h2>
<Outlet />
<div>
<button onClick={() => setSearchParams({ filter: 'active' })}>Active Users</button>
<button onClick={() => setSearchParams({})} >Reset Filter</button>
</div>
{
showActiveUsers ? (
<h2>Showing active users</h2>
) : (
<h2>Showing all users</h2>
)
}
</div>
)
}


Our code with search params is working as expected. Now using search patterns is pretty common when you have to apply filters on a listing page.

For example on a website like an amazon or an e-commerce site you'll have a list of parameters on the left-hand side selecting a filter will update the URL with a search param, this lets you share the link with others or even bookmark the link.

Hopefully, you now have an idea of how to implement such scenarios