Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Modify Query String | React Router
Expert React
course content

Conteúdo do Curso

Expert React

Expert React

1. React Key Concepts
2. React Router
3. Redux Toolkit
4. Formik
5. Jest
6. Next Steps

bookModify 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 variable searchQuery and its corresponding setter function setSearchQuery. The initial value of searchQuery 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 using trim().
  • Line 10-22: Rendering elements.

Step 2

Add useSearchParams functionality.

Code explanation:

  • Line 2: Import the useSearchParams hook from the react-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 variable searchParams and its corresponding setter function setSearchParams. The useSearchParams 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.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 9
some-alt