remix-run / react-router

Declarative routing for React

Home Page:https://reactrouter.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot pass props from <Route> to rendered `component`

Noitidart opened this issue · comments

Version

4.0.0-beta.7

Test Case


Steps to reproduce

Render <Route path="/" component={PageContent} pass_to_page_content="hi" exact/>

Expected Behavior

I expect that in this.props in PageContent I should have pass_to_page_content, however it is not there. In <= 4.0.0-beta.6 this worked.

Actual Behavior

The this.props of PageContent only has location and history. It does not get pass_to_page_content.

Was I using <Route> wrong?

This was intentional. See the comments where this change was made.

If you need to pass props, use render.

<Route exact path='/' render={(props) => (
  <PageContent {...props} pass_to_page_content='hi' />
)}/>

Aw darn it was super useful. I didn't realize it was undocumented. Thanks for the super fast reply.

God bless you @pshrmn for that snippet

<Route exact path="/profile" render={(props) => ( <Profile user={this.props.user}/> )} />

Here is what I ended up using

<Route exact path='/auth/login' render={(props) => <Login {...this.props} /> } />

Is there a way to pass automagically parent props to my route component ?

@DavidNorena i would look into using Redux .... that is the direction I am going in now with my project to accomplish "Global Props" if you will. He is the course I am taking from @StephenGrider
https://www.udemy.com/react-redux/learn/v4/overview

You could make use of Higher Order Components to wrap the component to be passed, and pass the props as an argument. This would make the code alot cleaner and more reusable.

For example

const AddPropsToRoute = (WrappedComponent, passedProps)=>{
    return (
        class Route extends Component{
            render(){
                let props = Object.assign({}, this.props, passedProps)
                return  <WrappedComponent {...props} />
            }
        }
    )
}

export default AddPropsToRoute

Then you can just use it as so:

let passingProps = {
        userName: 'uche'
    }

<Route path={`${match.path}/:id`} component={AddPropsToRoute(Users, passingProps)} />

Where Users is the component being passed.

I made a really simple npm package for that! You can check it here: https://www.npmjs.com/package/react-router-with-props

I hope it helps