Categories
React Answers

How to programmatically update query parameters in React Router?

Spread the love

Sometimes, we want to programmatically update query parameters in React Router.

in this article, we’ll look at how to programmatically update query parameters in React Router.

How to programmatically update query parameters in React Router?

To programmatically update query parameters in React Router, we cal call the history.replace method.

For instance, we write

import React from "react";
import { useHistory, useLocation } from "react-router";

const MyComponent = () => {
  const history = useHistory();
  const location = useLocation();

  const onChange = (event) => {
    const { name, value } = event?.target;
    const params = new URLSearchParams({ [name]: value });
    history.replace({ pathname: location.pathname, search: params.toString() });
  };

  return <input name="search" onChange={onChange} />;
};

to call history.replace in the onChange function to navigate after we change the input value.

We create the query string with the URLSearchParams constructor by calling it with an object with the query string key name and value value.

Then we call history.replace with an object with the search property set to the query string we created with params.toString to navigate with the query string.

Conclusion

To programmatically update query parameters in React Router, we cal call the history.replace method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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