Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Integrating useSearchParams Hook | Advanced React Router Concepts
React Router

bookIntegrating useSearchParams Hook

In the example component ProductsPage, we integrate useSearchParams to manage query parameters.

import React, { useState, useEffect } from "react";
import { useSearchParams } from "react-router-dom";

const ProductsPage = ({ data }) => {
const [companies, setCompanies] = useState(data);
const [searchParams, setSearchParams] = useSearchParams();

// Function to update the displayed `companies` based on query parameters
const updateCompanies = (params) => {
const filteredCompanies = data.filter((item) => {
const { companyName } = item;
if (params.get("name")) {
return companyName.toLowerCase().includes(params.get("name"));
}
return true;
});
setCompanies(filteredCompanies);
};

useEffect(() => {
// When the component mounts or query parameters change, update the displayed `companies`
updateCompanies(searchParams);
}, [searchParams, data]);

// Function to update query parameters based on user input
const handleChange = (e) => {
const newName = e.target.value;
setSearchParams({ name: newName });
};

return (
<>
<input
type="text"
value={searchParams.get("name") || ""}
onChange={handleChange}
/>
<ul className="companyList">
{companies.map(({ id, companyName, companyDescription }) => (
<li key={id}>
<h2>{companyName}</h2>
<p>{companyDescription}</p>
</li>
))}
</ul>
</>
);
};

Here's a breakdown of the code:

  1. We import the necessary dependencies: useState, useEffect, and useSearchParams from React Router;
  2. We initialize the state inside the component using useState. The companies state holds the data to be displayed, and we use the setCompanies function to update it;
  3. We create a function updateCompanies to filter the data based on query parameters. The function takes the current query parameters as a URLSearchParams instance and uses them to filter the data. In this case, it filters by the "name" parameter;
  4. We use the useEffect hook to run the updateCompanies function when the component mounts and whenever the query parameters change. This ensures that the displayed data is kept in sync with the URL;
  5. The handleChange function updates the "name" query parameter in response to user input. When the input field changes, it calls setSearchParams with the new parameter value;
  6. In the component's return statement, we render an input field for user input and a list of companies based on the filtered data.

This code demonstrates how to integrate useSearchParams and React Router to create a dynamic web application that responds to changes in query parameters.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 6
some-alt