Conteúdo do Curso
Expert React
Expert React
Modify Query String
To practice using the useSearchParams
hook, we will create a component that consists of a form with a single input field. This input field will represent a search query in our app, and our goal is to update the URL based on the input value.
Step 1
We would create the form as always with the useState
hook:
Code explanation:
- Line 1: This line imports the necessary dependencies, including the React library and the
useState
hook. - Line 3: It defines a functional component named
App
. - Line 4: This line utilizes the
useState
hook to declare a state variablesearchQuery
and its corresponding setter functionsetSearchQuery
. The initial value ofsearchQuery
is set to an empty string. - Line 6-8: This function updates the
searchQuery
state with the current value of the input field. Any leading or trailing whitespace is removed usingtrim()
. - Line 10-22: Rendering elements.
Step 2
Add useSearchParams
functionality.
Code explanation:
- Line 2: Import the
useSearchParams
hook from thereact-router-dom
package, which allows us to access and modify the URL search parameters. - Line 6: This line utilizes the
useSearchParams
hook to declare a state variablesearchParams
and its corresponding setter functionsetSearchParams
. TheuseSearchParams
hook returns an object representing the current search parameters in the URL and provides a way to update them. - Line 12-15: This function is an event handler triggered when the form is submitted. It updates the URL search parameters by setting the "query" parameter to the current value of
searchQuery
. - Line 17: This line logs the value of the "query" parameter in the URL search parameters to the console. So we can inspect it and see the result.
Complete code
Please take a moment to review the code and console carefully to observe how the searchParams
works.
Obrigado pelo seu feedback!