Reputation: 314
I have a app created from create-react-app and the prop location for all my components is always undefined..
Here is index.js
ReactDOM.render((
<BrowserRouter >
<App/>
</BrowserRouter>
), document.getElementById('root'));
registerServiceWorker();
Here is a short version of app.js
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
auth: UserProfile.getAuth(),
}
}
render() {
if(this.state.auth){
return (
<Router>
<Switch>
...
<Route path="/editUser" render={()=><EditUser className="App" app={this}/>} />
</Switch>
</Router>
);
}
else{
...
}
}
}
now here is editUser.jsx
class EditUser extends React.Component {
constructor(props) {
super(props);
...
}
componentDidMount(){
console.log(this.props.location) //undefined
}
render() {
return (<div>...</div>)
I keep getting undefined and I dont understand why...
I use "react-router-dom": "^4.3.1"
according to my package.json
Please help!
Upvotes: 1
Views: 4789
Reputation: 7189
You need to pass the router props into the component since you're using the render
prop of the <Route/>
component.
Also, In your App
component you don't need BrowserRouter as Router
since you're already wrapping <App/>
in index.js
. I changed the import
and removed the wrapping <Router/>
component.
import { Route, Switch } from 'react-router-dom';
class App extends React.Component {
...
render() {
if (this.state.auth) {
return (
<Switch>
...
<Route path="/editUser" render={props =>
<EditUser {...props} className="App" app={this}/>
}/>
</Switch>
);
}
}
}
Upvotes: 3
Reputation: 126
I think you need to use the withRouter HOC on your EditUser Component in order to inject props like location.
See react-router getting this.props.location in child components
Upvotes: 0