I am using this.props.history.push to pass props to components after submitting a form.
The submission of a form takes user to the home page (/home) but it also needs to pass props to NavBar component which is not included in the react-router routes.
this.props.history.push({
pathname: '/home',
propOne: propOneValue // <-- this prop must be received by NavBar component
})
I tried to do something like this:
...
}).then((response) => {
this.props.history.push({
pathname: '/home',
})
return <NavBar propOne={propOneValue} />
...
But this.props.propOne
in the NavBar (class based) component gets undefined. I think this might be caused by the fact that NavBar have been already rendered without props in one of the other components.
So my question is - can you use this.props.history.push to pass props to a different component than the pathname route one?
When using history to push, pass any data you want in the second argument for the push function
this.props.history.push('/yourPath', {prop1: someData});
and Then to access this data in the other component
const data = this.props.history.location.state;
// data will be {prop1: someData}
In the 2nd block that you just edited, as soon the response is coming in it is redirecting to /home so return statement is not called as it has been now landed to home page. that's the reason you are getting propOne as undefined. To use in Home page give the props value to home page and in home page render you can push the required props value to nav bar. Use this way to pass the props value :
this.props.history.push({
pathname: "/home",
state: {
propOne: propOneValue
}
});
And in Main Page to get the prop value: (if Main Page is a class based component else don't use this)
this.state = {
propValue: this.props.location.state.propOne,
}
then use the propValue
in the component.
Try to console.log(this.props.location)
and check what all the values you are getting to have clear view.
Main Page :
render() {
return (
<Nav propVal={this.state.propValue} />
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With