Integrating 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:
- We import the necessary dependencies:
useState,useEffect, anduseSearchParamsfrom React Router; - We initialize the state inside the component using
useState. Thecompaniesstate holds the data to be displayed, and we use thesetCompaniesfunction to update it; - We create a function
updateCompaniesto filter the data based on query parameters. The function takes the current query parameters as aURLSearchParamsinstance and uses them to filter thedata. In this case, it filters by the "name" parameter; - We use the
useEffecthook to run theupdateCompaniesfunction when the component mounts and whenever the query parameters change. This ensures that the displayed data is kept in sync with the URL; - The
handleChangefunction updates the "name" query parameter in response to user input. When the input field changes, it callssetSearchParamswith the new parameter value; - 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.
すべて明確でしたか?
フィードバックありがとうございます!
セクション 3. 章 6
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 3. 章 6