React router pass props to route component

前端 未结 2 765
耶瑟儿~
耶瑟儿~ 2021-02-06 17:25

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 \

相关标签:
2条回答
  • 2021-02-06 17:45

    <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
        };
    }
    
    0 讨论(0)
  • 2021-02-06 17:47

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

    0 讨论(0)
提交回复
热议问题