Reputation: 177
I'm trying to pass props from my app.jsx to one of my route components using react router but I get the following error
TypeError: Cannot read property 'acc' of undefined
Here's the code from my app.jsx:
<Route exact path='/FileUpload' acc={this.state.account} ethAdd={this.state.ethAddress} component={FileUpload} />
And the code in the component that route leads to:
constructor(props) {
super(props);
this.setState({
account: this.props.route.acc,
ethAddress: this.props.route.ethAdd
})
}
I don't really understand from reading other solutions on here how this passing of props in react router works, can anyone help me understand what I need to do?
Upvotes: 7
Views: 15220
Reputation: 554
Here are few ways you can pass props to a route component.
With the react-router v5, we can create routes by wrapping with a <Route>
component, so that we can easily pass props to the desired component like this.
<Route path="/">
<Home name="Sai" />
</Route>
Similarly, you can use the children prop in v5.
<Route path="/" children={ <Home name="Sai" />} />
If you are using react-router v4, you can pass it using the render prop.
<Route path="/" render={() => <Home name="Sai" />} />
(originally posted at https://reactgo.com/react-router-pass-props/)
Upvotes: 15
Reputation: 4977
<Route>
does not pass custom props to components. Use render function instead:
<Route exact path='/FileUpload' render={
(props) => <FileUpload {...props} acc={this.state.account} ethAdd={this.state.ethAddress} />
} />
As SakoBu mentioned you need to change your constructor:
constructor(props) {
super(props);
this.state = {
account: this.props.acc,
ethAddress: this.props.ethAdd
};
}
Upvotes: 15