Handling query parameters in React Router is essential for creating dynamic and user-friendly applications. Query parameters allow you to pass additional information in the URL, which can be used to filter data, manage state, or control the rendering of components. React Router provides a straightforward way to access these parameters, making it easier to build responsive applications.
To access query parameters in a React component, you can use the `useLocation` hook provided by React Router. This hook returns the current location object, which contains the search string representing the query parameters.
import { useLocation } from 'react-router-dom';
const MyComponent = () => {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const paramValue = queryParams.get('paramName'); // Replace 'paramName' with your query parameter key
return Value of paramName: {paramValue};
};
Consider a scenario where you want to filter a list of products based on a category passed as a query parameter. Here’s how you can implement it:
import React from 'react';
import { useLocation } from 'react-router-dom';
const ProductList = () => {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const category = queryParams.get('category');
const products = [
{ id: 1, name: 'Product A', category: 'electronics' },
{ id: 2, name: 'Product B', category: 'books' },
{ id: 3, name: 'Product C', category: 'electronics' },
];
const filteredProducts = category ? products.filter(product => product.category === category) : products;
return (
{filteredProducts.map(product => (
- {product.name}
))}
);
};
In summary, managing query parameters in React Router is a powerful way to enhance your application's functionality. By leveraging the `useLocation` hook and following best practices, you can create a seamless user experience while avoiding common pitfalls.