Using Search Params with useSearchParams

Loading

Using useSearchParams in React (React Router v6+)

In React Router v6 and above, the useSearchParams hook provides an easy way to work with the query string parameters in the URL. It allows you to read and manipulate the search parameters (also known as query parameters) in the URL without needing to manually parse the window.location.search.

What is useSearchParams?

useSearchParams is a hook provided by React Router v6+ that simplifies the manipulation of the query string in the URL. You can use it to:

  • Read query parameters.
  • Modify query parameters.
  • Update the URL with new query parameters without reloading the page.

Basic Usage of useSearchParams

The useSearchParams hook returns an array with two values:

  1. searchParams: An object that provides access to the current search parameters as a URLSearchParams instance.
  2. setSearchParams: A function used to update the query parameters.

Example: Reading and Updating Query Parameters with useSearchParams

  1. Basic Setup: Using useSearchParams
import React, { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useSearchParams } from 'react-router-dom';

const HomePage = () => {
  // Using useSearchParams to read and manipulate query params
  const [searchParams, setSearchParams] = useSearchParams();
  const search = searchParams.get("search") || ""; // Retrieve "search" query param

  const handleSearchChange = (e) => {
    // Update the "search" query param when the input changes
    setSearchParams({ search: e.target.value });
  };

  return (
    <div>
      <h1>Home Page</h1>
      <input
        type="text"
        value={search}
        onChange={handleSearchChange}
        placeholder="Enter search term"
      />
      <p>Searching for: {search}</p>
      <Link to="/">Go Home</Link>
    </div>
  );
};

const AboutPage = () => {
  const [searchParams] = useSearchParams();
  const search = searchParams.get("search") || ""; // Retrieve "search" query param
  return <h2>About Page - Search Term: {search}</h2>;
};

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/about" element={<AboutPage />} />
      </Routes>
    </Router>
  );
};

export default App;

Explanation:

  • useSearchParams():
    • searchParams contains the current query string parameters as a URLSearchParams object.
    • setSearchParams allows you to update the query parameters and the URL without a full page reload.
  • Reading Query Params: You can retrieve a specific query parameter using searchParams.get('paramName').
  • Updating Query Params: You can update the query parameter with setSearchParams({ paramName: value }), which automatically updates the URL.

Example: Multiple Query Parameters

You can handle multiple query parameters using useSearchParams as well. If you have multiple parameters to manipulate, you can update them individually or all at once.

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useSearchParams } from 'react-router-dom';

const HomePage = () => {
  const [searchParams, setSearchParams] = useSearchParams();

  const search = searchParams.get("search") || "";
  const page = searchParams.get("page") || 1;

  const handleSearchChange = (e) => {
    setSearchParams({ search: e.target.value, page: 1 });
  };

  const handlePageChange = (e) => {
    setSearchParams({ search, page: e.target.value });
  };

  return (
    <div>
      <h1>Home Page</h1>
      <input
        type="text"
        value={search}
        onChange={handleSearchChange}
        placeholder="Enter search term"
      />
      <div>
        <label>Page: </label>
        <input
          type="number"
          value={page}
          onChange={handlePageChange}
        />
      </div>
      <p>Searching for: {search}</p>
      <p>Page: {page}</p>
      <Link to="/">Go Home</Link>
    </div>
  );
};

const AboutPage = () => {
  const [searchParams] = useSearchParams();
  const search = searchParams.get("search") || "";
  const page = searchParams.get("page") || 1;

  return <h2>About Page - Search Term: {search} | Page: {page}</h2>;
};

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/about" element={<AboutPage />} />
      </Routes>
    </Router>
  );
};

export default App;

Explanation:

  • Multiple Parameters: In this example, we’re managing both search and page query parameters. You can update one without affecting the other.
  • Updating URL: The input field changes the search parameter, and the page number is handled with another input field, reflecting changes directly in the URL.

Example: Using Search Params for Filtering and Pagination

This is a common use case where search parameters are used to filter items and paginate through them.

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useSearchParams } from 'react-router-dom';

const ProductList = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  
  const category = searchParams.get('category') || 'All';
  const page = searchParams.get('page') || 1;

  const handleCategoryChange = (e) => {
    setSearchParams({ category: e.target.value, page });
  };

  const handlePageChange = (e) => {
    setSearchParams({ category, page: e.target.value });
  };

  return (
    <div>
      <h1>Product List</h1>
      <div>
        <label>Category:</label>
        <select value={category} onChange={handleCategoryChange}>
          <option value="All">All</option>
          <option value="Electronics">Electronics</option>
          <option value="Clothing">Clothing</option>
        </select>
      </div>
      <div>
        <label>Page:</label>
        <input type="number" value={page} onChange={handlePageChange} min="1" />
      </div>
      <p>Filtering by: {category}</p>
      <p>Page: {page}</p>
      <Link to="/about">Go to About</Link>
    </div>
  );
};

const AboutPage = () => {
  const [searchParams] = useSearchParams();
  const category = searchParams.get('category') || 'All';
  const page = searchParams.get('page') || 1;

  return (
    <div>
      <h2>About Page</h2>
      <p>Category: {category}</p>
      <p>Page: {page}</p>
    </div>
  );
};

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<ProductList />} />
        <Route path="/about" element={<AboutPage />} />
      </Routes>
    </Router>
  );
};

export default App;

Explanation:

  • Category and Page: This example allows filtering products by category and controlling pagination using query parameters.
  • Handling Search Params: Both the category and page are handled as query parameters, and the UI reflects these parameters, while the URL is updated as the user interacts with the filters.

Key Points with useSearchParams

  • searchParams.get(name): Retrieves the value of the specified query parameter.
  • setSearchParams({ param: value }): Updates the query parameters in the URL. React Router will re-render the components as necessary.
  • useSearchParams allows URL manipulation without page reloads, providing an SPA-like experience while maintaining the URL state.

Leave a Reply

Your email address will not be published. Required fields are marked *