简体   繁体   中英

How do I pass props down from react-router-doms's render?

I am aware that to pass down props to my Routes I need to use the render. For example:

const BaseRouter = (props) => (

    <div>
        {console.log(props)} // this displays everything I need, including props.username
        <Route exact path='/room/' render={(props) => <Room {...props} />} />
    </div>
);

The problem is that inside my Room component, the only props passed down are history, location, and match (these come straight from react-router-dom).

I have also tried manually passing the props needed down:

<Route exact path='/room/' render={(props) => <Room {...props} username={props.username} />} />

But inside Room, I still get undefined for props.username. Any ideas?

You need to give a different name to you variables. Doing render={(props) => <Room {...props} /> will always pass the router props, that is why props.username is undefined.

const BaseRouter = (props) => (

    <div>
        <Route exact path='/room/' render={(routeProps) => <Room {...routeProps} {...props} />} />
    </div>
);

Route component takes children as well.

 const BaseRouter = (props) => ( <div> {console.log(props)} // this displays everything I need, including props.username <Route exact path='/room/'> <Room {...props}/> </Route> </div> );

In Room component you can use useHistory, useLocation and useRouteMatch hooks. If Room is class based component then withRouter HOC is also useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM