6

Somewhere in component 1, I have this:

if (redirectToReferrer) {
    return <Redirect to={{
          pathname: "/test/new",
          state: { event: "test" }
     }} />;
}  

In my component 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 component. This new referrer key (which is not a special name) would then be accessed via this.props.location.state.referrer in the Login component pointed to by the pathname '/login'

Why is this.props.location undefined?

kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131

3 Answers3

6

Ensure "/test/new" is defined by a <Route/> component in App.js or wherever you have defined the routes.

<Route path="/test/new" component={NewTestComp}/>

If you've defined the using the render method make sure you are passing the props to your component like this.

<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>
Anand Naik B
  • 689
  • 1
  • 7
  • 20
0

Technically components directly routed like this:

<Route path="/about" component={About} />

has props provided by react router such as location so make sure wherever you are redirecting, that component has a route defined.

Lelouch
  • 910
  • 6
  • 19
0

Upgrade to the latest version of react-router-dom. Currently on version 5.2.0

Kevin Kiwango
  • 111
  • 1
  • 4