Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router pass props to route component

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?

like image 819
Neil Grogan Avatar asked Mar 24 '19 21:03

Neil Grogan


People also ask

How do you pass props in react router route?

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.

Can we pass props in route?

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.

How do you pass props to a component rendered by react router v6?

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 .

How do you pass props to a component?

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.


1 Answers

<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
    };
}
like image 70
UjinT34 Avatar answered Oct 19 '22 15:10

UjinT34