Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

React Routing

Why is this causing an error with
“this.props.history.push(path);”

when using Route like this: <Route exact path=“/search” render={() => <SearchForm />} />

but this is not causing an error: <Route exact path=“/search” component={SearchForm} />

1 Answer

Jesus Mendoza
Jesus Mendoza
23,275 Points

Thats because when you use render method in react router, props are passed to the render as an parameter like this

<Route exact path=“/search” render={() => <SearchForm />} /> // Your render function is not receiving props

In order for it to work you should pass the props to the component like this

<Route exact path=“/search” render={(props) => <SearchForm {...props}/>} /> // The render function receives props and pass it down to the SearchForm component

However, when you use the component method in react router, props are passed directly to the component

<Route exact path=“/search” component={SearchForm} /> //props are passed directly to searchForm

That's why you have access to this.props.history.push when you use the component method

Thank you very much for the explanation!