How To Programmatically Update Query Params In React Router

Programmatically update query params in React router

If you don’t know how to how to programmatically update query params in React router, don’t worry. We will give you some solutions in this article. Read on it.

React Router 

The React routing library, known as React Router, lets you switch between different views of a React app’s components, changes the browser’s URL, and keeps the UI in sync with the URL.

Terminal:

npm install react-router-dom –save

The main components of ReactJs Router are:

  • BrowserRouter: a router implementation that uses the pushState, ReplaceState, and pop state events provided by the HTML5 history API to keep your user interface in sync with URLs.
  • Route: When its path matches the current URL, a conditionally rendered component called Route will display some UI.
  • Link: The Link component implements navigation throughout the application and creates links to various routes. It functions similarly to the HTML link tag.
  • Switch: Instead of showing all the routes that match, the Switch component is only used to show the first Route that matches the location. Despite not matching LINKs, none of the app’s SWITCH token challenge functions is utilized here. However, if we have a route (remember that there is no EXACT here), then all tags for that Route will be processed beginning with “/” (all routes begin with “/”).In this case, only one of the statements can be processed without using the SWITCH statement.

UseSearchParams() in React Router

We can use the useSearchParams() function that React Router v6 provides to read the necessary query string search parameters from the URL.

We will also look into a few additional options, including the ability to read a query parameter individually or simultaneously.

Code:

import {
  useSearchParams,
} from 'react-router-dom';
import React from 'react';
export default function App() {
  const [userSearchparams] = useSearchParams();
  alert(userSearchparams);
  return <div>useSearchParams</div>;
}

We can create an URLSearchParams object using the useSearchParams hook in this example.

Programmatically update query params in React router

Use useNavigate() hook

You can also use the useNavigate() hook to solve this problem. 

The example below will show you how it works.

Code:

import {useNavigate} from 'react-router-dom';
export default function App() {
  const navigation = useNavigate();
  const handleClick = () => {
    navigation({pathname:'/Info', search: '?query=name&page=10'});
  };
  return (
    <div>
      <button onClick={handleClick}>Navigate to Infopage</button>
    </div>
  );
}

In the above example, we define navigation as useNavigate() hook, then use it to direct the application to the page “/Infor?query=abc&page=10” after the user clicks on the navigate button. We set the query params in the handleClick function.

Use the useSearchParams() hook

To solve this problem, you can use the useSearchParams() hook in React router. Look at the example below to know how it works. 

Code:

import React from "react";
import { useSearchParams } from "react-router-dom";
export default function App() {
  const [searchParams, setSearchParams] = useSearchParams();
  const handleOnClick = () => {
    setSearchParams({ myParam: "Original param" });
  };
  const handleOnChange = (event) => {
    setSearchParams({ query: event.target.value });
  };
  console.log(searchParams.get("query"));
  return (
    <div>
      <button onClick={handleOnClick}>Update Query params</button>
      <input id="search-input" onChange={handleOnChange} />
    </div>
  );
}

In this example, we define the useSearchParams() hook to create an URLSearchParams object, and we set query params programmatically with the function handleOnChange. When the input listens for the onchange event, it automatically assigns the value of the input cell to the query params. So you can see the URL update automatically when you type in the search input.

Summary

To summarize, many ways to programmatically update query params in React router. But in this article, we show you some easy ways to do it, like using the useNavigate() hook or the useSearchParams() hook.

Maybe you are interested:

Leave a Reply

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