Ask Your Question
0

How can I use React Router v4 to redirect to the same route but with different query parameters?

asked 2022-02-09 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-05-22 23:00:00 +0000

huitzilopochtli gravatar image

You can use the withRouter higher-order component provided by react-router-dom to access the history object and use history.push() to redirect to the same route with different query parameters.

Example:

import React from 'react';
import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  handleRedirect = () => {
    const { history } = this.props;
    history.push({
      pathname: '/my-route',
      search: '?param=value',
    });
  }

  render() {
    return (
      <button onClick={this.handleRedirect}>Redirect</button>
    );
  }
}

export default withRouter(MyComponent);

In this example, the handleRedirect function uses history.push() to redirect to the same route (/my-route) but with a query parameter of param=value. The withRouter higher-order component is used to inject the history object as a prop into the component.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-09 11:00:00 +0000

Seen: 1 times

Last updated: May 22 '21