In this post we'll see how to handle URL search parameters or query parameters using useSearchParams() hook in React Router.
What are query parameters
Query parameters are used to pass data in a URL. These parameters are added to the URL after a question mark in the form of key-value pair. You can pass multiple parameters in a URL in that case parameters are separated by an ampersand ('&').
http://example.com/search?name=react&category=web
In the above URL name and category are query parameters with values as react and web respectively.
useSearchParams hook to handle query parameters
Using useSearchParams in React Router you can access and modify query parameters. useSearchParams hook returns an array with two elements; search parameters of the current URL and a function to update them. Using array destructuring you can assign these 2 elements to two variables.
const [searchParams, setSearchParams] = useSearchParams();
You can initialize the search params with a default value, if needed.
const [searchParams, setSearchParams] = useSearchParams("?name=react");
You can access the value of any search parameter by passing the key to get method.
const searchedLanguage = searchParams.get('name'); const searchedCategory = searchParams.get('category');
By using setSearchParams which is a function ( second element in the array retruned by useSearchParams()), you can update the query parameters
setSearchParams({ name: "angular" });You can also update multiple values or even append a new one.
setSearchParams({ name: "angular", category:"web" });
useSearchParams to access query parameter React example
In the example we'll have a ProductSearch component where user can enter the name of the product. Entered product name is added to the URL as a search param and Product component is called to find the searched product in an array of products.
Route configuration
Routes for the above mentioned components can be configured as-
<Route path="product" element={<RouteProduct />} /> <Route path="productSearch" element={<ProductSearch />} />
Components
src\components\routes\ProductSearch.js
import { useNavigate } from "react-router"; import { useState } from "react"; const ProductSearch = () => { const [pName, setpName] = useState(''); const navigate = useNavigate(); const ProductChangeHandler = (event) => { event.preventDefault(); setpName(event.target.value); } const searchHandler = () => { navigate(`/product?productName=${pName}`); } return ( <> <h2>Product Search</h2> <div> <input type="text" value={pName} placeholder="Enter product name" onChange={ProductChangeHandler}/> <button type="button" onClick={searchHandler}>Search</button> </div> </> ) } export default ProductSearch;
Points to note here-
- There is an input element where user can enter the searched product.
- State of the searched product is saved in pName variable.
- Using useNavigate() user is programmatically navigated to the path
`/product?productName=${pName}`
where product name is added as a search parameter in the URL.
src\components\routes\RouteProduct.js
import { useSearchParams } from "react-router"; export const DUMMY_PRODUCTS = [ {id:1, name:'Laptop', price:455.50}, {id:2, name:'Mouse', price:15.89}, {id:3, name:'USB', price:10.00}, {id:4, name:'HDD', price:55.50} ]; const RouteProduct = () => { const [searchParams, setSearchParams] = useSearchParams(); const searchText = searchParams.get('productName'); //console.log('' , searchText) const products = DUMMY_PRODUCTS.filter(product => product.name.toLowerCase() === searchText.toLowerCase()); return( <> <div className= "row"> <div className="col-sm-6"> <ul className="list-group"> {products.map(product => <li className="list-group-item" key={product.id}>{product.name} {product.price}</li> )} </ul> </div> </div> </> ) } export default RouteProduct;
Points to note here-
- A hardcoded array of products is used here against which search will be done.
- useSearchParams() hook is used here to extract the search parameter value from the URL.
const searchText = searchParams.get('productName');
- Bootstrap 5 is used for styling here.
Product search page
After clicking search button
This type of filtering functionality gives a better user experience if done in the same page. Refer post- Search Filter Using useSearchParams in React Router to see how to implement search filtering.
That's all for this topic useSearchParams in React Router - Handling Query Parameters. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment