Michael Skarn
Michael Skarn

Reputation: 65

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?

Upvotes: 0

Views: 116

Answers (2)

gautamits
gautamits

Reputation: 1292

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.

Upvotes: 0

Jagrati
Jagrati

Reputation: 12222

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

Upvotes: 1

Related Questions