Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use this.props.history.push to pass props to a different component than the pathname says?

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?

like image 326
SevenNationS Avatar asked Sep 14 '25 21:09

SevenNationS


2 Answers

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}
like image 75
Ebrahim Saed Avatar answered Sep 17 '25 12:09

Ebrahim Saed


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}  />
        )
    }
like image 25
Ayushi Keshri Avatar answered Sep 17 '25 13:09

Ayushi Keshri