7
votes

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?

2
Consider redux or some other state management. Pretty sure I can guess what you're doing and it's going to get really complex really quick! If not, the answer below is how you pass custom stuff to routes - Predrag Beocanin
The answer below is correct... The only thing I would add is the constructor is where you initialize your state this.state = {...} not setState... - SakoBu
Have 15 days left of this project so perhaps a bit too late to learn redux... what I'm trying to do is have my app.jsx always maintain the users Metamask account so I can then pass it to that page. I know this might not be the best way to do this but I was having great issues trying to get this to work in that component - Neil Grogan

2 Answers

15
votes

<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
    };
}
10
votes

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/)