Divakar R
Divakar R

Reputation: 81

How to pass props to routes using redirect

I am working on a reactjs project where i have to pass props form component A to Component B now , Component A has the following code inside render function:

{this.state.showComponentedit ?
<div>
<Redirect to={'/editB'} editdata={this.state.feedData} />: null
</div>
}

I am getting the current data passed by B in A component using following code:

// inside a random function which will be invoked on button press
console.log("Props from B", this.props.edidata);

The edidata is null in Component A. how can i get the value when i am invoking the rooute "editB" and use that value in component B. Thank you

Upvotes: 0

Views: 3882

Answers (3)

Yan Huang
Yan Huang

Reputation: 41

Maybe you can do this:

<Redirect
  to={{
    pathname: "/login",
    search: "?utm=your+face",
    state: { referrer: currentLocation }
  }}
/>

The state object can be accessed via this.props.location.state in the B component.

More details: https://reacttraining.com/react-router/web/api/Redirect/to-object

Upvotes: 1

Muhammad Bilal
Muhammad Bilal

Reputation: 341

You can also pass an object to 'to' prop of Redirect like this:

<Redirect to={{
  pathname='/editB'
  state={
    editdata: this.state.feedData
  }
}}/>

After that in editB component you can get the data from:

this.props.location.state

I hope this approach will solve your problem.

Upvotes: 1

Chriss Hd
Chriss Hd

Reputation: 643

First you have to make the data from B accessible to A

You can do that by lifting the data to the parent component and then passing that data to A using Route

 <Route
   exact={true}
   path="/mycomponent"
   render={props => <EditComponent editData={this.state.feedData} />}
 />

Upvotes: 0

Related Questions