Somewhere in ponent 1, I have this:
if (redirectToReferrer) {
return <Redirect to={{
pathname: "/test/new",
state: { event: "test" }
}} />;
}
In my ponent 2, I have this:
constructor(props){
super(props);
console.log(this.props.location) //undefined
}
According to the docs, this should work.
The state object can be accessed via this.props.location.state in the redirected-to ponent. This new referrer key (which is not a special name) would then be accessed via this.props.location.state.referrer in the Login ponent pointed to by the pathname '/login'
Why is this.props.location
undefined?
Somewhere in ponent 1, I have this:
if (redirectToReferrer) {
return <Redirect to={{
pathname: "/test/new",
state: { event: "test" }
}} />;
}
In my ponent 2, I have this:
constructor(props){
super(props);
console.log(this.props.location) //undefined
}
According to the docs, this should work.
The state object can be accessed via this.props.location.state in the redirected-to ponent. This new referrer key (which is not a special name) would then be accessed via this.props.location.state.referrer in the Login ponent pointed to by the pathname '/login'
Why is this.props.location
undefined?
- did you want to pass state to the other ponent or you just need to location (path) ? – Amir Mohammad Moradi Commented May 14, 2018 at 11:09
-
@AmirmohammadMoradi I want to be able to access the state in my second ponent, like it's mentioned in the docs via:
this.props.location.state.event
– kockburn Commented May 14, 2018 at 11:10 - did you test { browserHistory } ? – Amir Mohammad Moradi Commented May 14, 2018 at 11:12
- based on stackoverflow./questions/41466055/… your code should work. can u upload your code on fiddle or sandbox to see? – Amir Mohammad Moradi Commented May 14, 2018 at 11:17
- 1 @AmirmohammadMoradi apparently it was deprecated, and replcaed by BrowserRouter – kockburn Commented May 14, 2018 at 11:29
3 Answers
Reset to default 6Ensure "/test/new" is defined by a <Route/>
ponent in App.js or wherever you have defined the routes.
<Route path="/test/new" ponent={NewTestComp}/>
If you've defined the using the render method make sure you are passing the props to your ponent like this.
<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>
Technically ponents directly routed like this:
<Route path="/about" ponent={About} />
has props provided by react router such as location so make sure wherever you are redirecting, that ponent has a route defined.
Upgrade to the latest version of react-router-dom. Currently on version 5.2.0