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.
Asked: 2022-02-09 11:00:00 +0000
Seen: 1 times
Last updated: May 22 '21