Smooth navigation and dynamic information display are essential when developing web apps to ensure users have a positive experience. All this can be done with the help of React Router, a popular tool for controlling routing in React apps.
But to fully utilize React Router, you must know how to manipulate query parameters, also known as search params. You will learn how to use react-router query parameters in all forms by reading this article.
We will cover six ways to establish React router query params that will help you kickstart your career in developing React applications. Accessing multiple query parameters, default values, and numeric and boolean queries are some of the ways that will be discussed in the article.
A JavaScript framework called React Router enables us to manage client-side and server-side routing for React apps. It makes creating single-page mobile apps or web applications possible, allowing page navigation without refreshing.
Additionally, it keeps the appropriate application view while enabling us to utilize browser history capabilities.
Table of Contents
Understanding Query Strings
Before we further the article, you must know what Query strings are. What task do they perform? What are the uses? How are they helpful?
Key-value pairs included in a URL and separated by ampersands (&) and a question mark (?) are called Query Strings. Data is sent to a web server or web application via them. For example, in the URL https://example.com/search?q=react+router&page=1, the query string is q=react+router&page=1. In this case, the keys are q and page; their corresponding values are react+router and 1.
Query parameters in the context of React Router offer an approach to customize your application’s behavior dynamically. Knowing how to extract and manipulate these query parameters is essential for any task involving the creation of user profiles, search feature implementation, or product filtering on e-commerce sites.
Visit: Understanding Query Strings
Setting up React Router
Before dealing with query parameters, ensure your project configures the React Router correctly. Using npm or yarn, install React Router if you haven’t already:
- Npm install react-router-dom or,
- Yarn add react-router-dom
Let us first establish a typical and basic react-router
import React from ‘react’;
import { BrowserRouter as Router, Route, Switch } from ‘react-router-dom’;
function App() { return ( <Router> <Switch> <Route path="/" component={Home} /> <Route path="/products" component={Products} /> {/* You can add more routes based on your application's requirements */} </Switch> </Router> ); }
export default App;
After setting up the basic react-router, we will discuss the different ways to manipulate query parameters.
Top 3 React-Router Query Parameters:
Let’s discuss each one of them in detail:
Handling Multiple Query Parameters
When working with numerous data from the URL, handling multiple query parameters in the React Router is frequently necessary. In this case, you may extract each query parameter independently using the “URLSearchParams” API. Here’s an illustration of how to use code to handle numerous query parameters:
Let’s say your website’s URL looks something like this: https://example.com/products?category=electronics&sortBy=price&page=2.
The category, sortBy, and page query parameters are what you wish to extract.
import React from ‘react’;
import { useLocation } from ‘react-router-dom’;
function Products() { const location = useLocation(); const searchParams = new URLSearchParams(location.search); // Accessing multiple query parameters const category = searchParams.get('category'); const sortBy = searchParams.get('sortBy'); const page = searchParams.get('page'); return ( <div> <h1>Products</h1> <p>Category: {category}</p> <p>Sort By: {sortBy}</p> <p>Page: {page}</p> </div> ); }
export default Products;
In the URL example.com/products?category=electronics&page=2¶mName=123this part of the display will show:
- Parameter Name: ‘123’
- Category: ‘electronics’
- Page: ‘2’
See Also: Understanding React Spread Props
Handling Default Values
In some circumstances, you should supply default values for query parameters if the URL doesn’t contain them. When using searchParams.get to do this, you may use the || operator to offer fallback values. For instance:
import React from ‘react’;
import { useLocation } from ‘react-router-dom’;
function Products() { const location = useLocation(); const searchParams = new URLSearchParams(location.search); const paramName = searchParams.get('paramName') || 'Default Value'; const category = searchParams.get('category') || 'Default Category'; const page = searchParams.get('page') || 1; return ( <div> <h1>Products</h1> <p>Parameter Name: {paramName}</p> <p>Category: {category}</p> <p>Page: {page}</p> </div> ); }
export default Products;
The component will show the default value without a query parameter in the URL. If the URL is https://example.com/products?page=2, for instance it will show:
- Parameter Name: ‘Default Value’
- Category: ‘Default Category’
- Page: ‘2
See Also: Render HTML Strings With React: Boost Your Web Development
Working with Numeric and Boolean Query Parameters
Although strings frequently represent query parameters, you may occasionally need to work with numeric or boolean values. You may utilize JavaScript’s built-in conversion methods, such as parseInt, parseFloat, and JSON.parse for boolean values, to convert query arguments to the right kinds.
Here is an illustration of how to handle boolean and numeric query parameters:
import React from ‘react’;
import { useLocation } from ‘react-router-dom’;
function Products() { const location = useLocation(); const searchParams = new URLSearchParams(location.search); // Parse numeric query parameters const page = parseInt(searchParams.get('page')) || 1; // Parse boolean query parameters const isActive = searchParams.get('isActive') === 'true'; return ( <div> <h1>Products</h1> <p>Page: {page}</p> <p>Is Active: {isActive ? 'Yes': 'No'}</p> </div> ); }
export default Products;
The component will show the following in the URL https://example.com/products?page=2&isActive=true:
- Page: 2
- Is Active: Yes
See Also: Character Functions In SQL: Manipulating Text In Databases
Updating Parameter
While accessing query parameters is helpful, it’s also critical to understand how to add or edit query parameters in your application dynamically. This is possible with React Router thanks to a combination of hooks and functions.
You want to design a link that adds a sortBy query parameter to the current URL when clicked by a user. To access the history object and change the URL, utilize the useHistory hook. Here is how to go about it:
import React from ‘react’;
import { useLocation, useHistory } from ‘react-router-dom’;
function Products() { const location = useLocation(); const searchParams = new URLSearchParams(location.search); const history = useHistory(); const sortBy = searchParams.get('sortBy') || 'default'; const handleSort = (sortByValue) => { // Update the URL with the new sortBy parameter searchParams.set('sortBy', sortByValue); history.push({ search: searchParams.toString() }); }; return ( <div> <h1>Products</h1> <p>Sort By: {sortBy}</p> <button onClick={() => handleSort('price')}>Sort by Price</button> <button onClick={() => handleSort('rating')}>Sort by Rating</button> </div> ); }
export default Products;
In this illustration, we access the history object using the use history hook. The handle sort method modifies the URL by supplying the desired value for the sortBy query parameter and using history.push to push the changed URL to the history object. This enables you to change the query parameters on the fly in response to user input.
See Also: Kotlin Function Overloading: Things To Know
FAQs
What are search params?
In a nutshell, SearchParams is a JavaScript object that handles and works with URL query parameters. It enables quick retrieval, updating, and manipulation of key-value pairs in a URL's query string. This is very helpful in web development for activities like dynamically altering query parameters or extracting data from URLs.
What do you mean by query strings?
A query string, in essence, is a portion of a URL comprising data in the form of key-value pairs separated by ampersands. It's frequently used for web development jobs, including searching, filtering, pagination, and customizing. It sends information from a web browser to a web server or web application.
What are ways you can establish query strings in the react-router?
You can do this in three ways Handling multiple Query parameters Handling null values Handling numeric and boolean parameters
Conclusion
React applications’ routing management is made more accessible by the flexible framework known as React Router.
Building dynamic single-page apps requires query parameters (search params), making features like filtering, pagination, and customization possible. This tutorial examined how to use React Router’s query parameters efficiently.
See Also: OnBlur Vs OnChange In React: Event Handling In Modern Web Apps