Conteúdo do Curso
React Router
React Router
Integrating useSearchParams Hook
In the example component ProductsPage
, we integrate useSearchParams
to manage query parameters.
Here's a breakdown of the code:
- We import the necessary dependencies:
useState
,useEffect
, anduseSearchParams
from React Router; - We initialize the state inside the component using
useState
. Thecompanies
state holds the data to be displayed, and we use thesetCompanies
function to update it; - We create a function
updateCompanies
to filter the data based on query parameters. The function takes the current query parameters as aURLSearchParams
instance and uses them to filter thedata
. In this case, it filters by the "name" parameter; - We use the
useEffect
hook to run theupdateCompanies
function when the component mounts and whenever the query parameters change. This ensures that the displayed data is kept in sync with the URL; - The
handleChange
function updates the "name" query parameter in response to user input. When the input field changes, it callssetSearchParams
with 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.
Obrigado pelo seu feedback!