How can we pass parameter with this.props.history.push('/page')
in React-Router v4?
.then(response => {
var r = this;
if (response.status >= 200 && response.status < 300) {
r.props.history.push('/template');
});
Add on info to get query parameters.
For more info about URLSearchParams check this link URLSearchParams
First of all, you need not do
var r = this;
as this inif statement
refers to the context of the callback itself which since you are using arrow function refers to the React component context.According to the docs:
So while navigating you can pass props to the history object like
or similarly for the
Link
component or theRedirect
componentand then in the component which is rendered with
/template
route, you can access the props passed likeAlso keep in mind that, when using history or location objects from props you need to connect the component with
withRouter
.As per the Docs:
If you need to pass URL params
theres a great post explanation by Tyler McGinnis on his site, Link to the post
here are code examples:
on the history.push component:
this.props.history.push(/home:${this.state.userID})
on the router component you define the route:
<Route path='/home:myKey' component={Home} />
on the Home component:
componentDidMount(){ const { myKey } = this.props.match.params console.log(myKey ) }
It is not necessary to use withRouter. This works for me:
In your parent page,
Then in ComponentA or ComponentB you can access
object, including the this.props.history.push method.