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

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:

import React, { useState } from "react";

const App = () => {
  const [searchQuery, setSearchQuery] = useState("");

  const onChange = (e) => {
    setSearchQuery(e.target.value.trim());
  };

  return (
    <form>
      <input
        type="text"
        name="search"
        onChange={onChange}
        value={searchQuery}
      />
      <button type="submit">Search</button>
    </form>
  );
};

export default App;

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.

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

const App = () => {
  const [searchQuery, setSearchQuery] = useState("");
  const [searchParams, setSearchParams] = useSearchParams();

  const onChange = (e) => {
    setSearchQuery(e.target.value.trim());
  };

  const onSubmit = (e) => {
    e.preventDefault();
    setSearchParams({ query: searchQuery });
  };

  console.log(searchParams.get("query"));

  return (
    <form onSubmit={onSubmit}>
      <input
        type="text"
        name="search"
        placeholder="Enter a movie title"
        onChange={onChange}
        value={searchQuery}
      />
      <button type="submit">Search</button>
    </form>
  );
};

export default App;

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

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Awesome!

Completion rate improved to 1.96

bookModify Query String

Deslize para mostrar o menu

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:

import React, { useState } from "react";

const App = () => {
  const [searchQuery, setSearchQuery] = useState("");

  const onChange = (e) => {
    setSearchQuery(e.target.value.trim());
  };

  return (
    <form>
      <input
        type="text"
        name="search"
        onChange={onChange}
        value={searchQuery}
      />
      <button type="submit">Search</button>
    </form>
  );
};

export default App;

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.

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

const App = () => {
  const [searchQuery, setSearchQuery] = useState("");
  const [searchParams, setSearchParams] = useSearchParams();

  const onChange = (e) => {
    setSearchQuery(e.target.value.trim());
  };

  const onSubmit = (e) => {
    e.preventDefault();
    setSearchParams({ query: searchQuery });
  };

  console.log(searchParams.get("query"));

  return (
    <form onSubmit={onSubmit}>
      <input
        type="text"
        name="search"
        placeholder="Enter a movie title"
        onChange={onChange}
        value={searchQuery}
      />
      <button type="submit">Search</button>
    </form>
  );
};

export default App;

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