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?
One way to do would be to pass the component prop an inline function. When you use component, the router uses React. createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render.
To get around this, you'd have to use Route s render prop. However, with React Router v6, since you're in charge of creating the element, you just pass a prop to the component as you normally would.
If you need to access the v6 versions of these objects you will use the React hooks, useNavigate for a navigate function which replaced the history object, useParams for params instead of match. params , and useLocation for location .
To pass props, add them to the JSX, just like you would with HTML attributes. To read props, use the function Avatar({ person, size }) destructuring syntax. You can specify a default value like size = 100 , which is used for missing and undefined props.
<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
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With