Ravenous part 3 - searchYelp method in App.js?

I am having trouble understanding the interaction between the components.

It seems more logical to me to have the searchYelp() method in SearchBar.js instead we have to put it in App.js

Would it be possible to have the searchYelp() method in SearchBar.js and how would you do that?

Can anyone provide an explanation?

Hi there.

I am fairly new to React, so my understanding and explanation may be wrong, but…

Having the searchYelp() function defined in the App component is, I think, an example of the programming pattern you’re introduced to in the Child Components Update their Siblings’ Props lesson.

The App component is stateful, and its state contains the property businesses which is where the list of businesses we want to display is stored. As a result, if we want to update that array, we need to set the state of the App component - meaning that we need to call this.setState() from inside the App component.

For this reason, searchYelp() is defined in App.js and the keyword this is bound to App.

The searchYelp() function is handed down to the SearchBar component, because the SearchBar is where the input fields are. When you actually do the search, the searchYelp() function gets its parameters from the SearchBar component but it changes the state of it’s parent - the App component.

Changing the state of App triggers React to render the component again, to reflect any changes. SearchBar won’t have changed, but the value of this.state.businesses which is passed to the BusinessList component as a prop has changed. BusinessList gets rendered again, with the data returned from Yelp.

Again, I’m new to React, but I don’t think there’s any way of directly accessing the state of the parent component from a child component. That’s why it’s necessary to pass a callback function as a prop, with this appropriately bound. This is why I don’t think you could put the searchYelp() function in the SearchBar, because it would no longer be able to update the state for the App component which is where the BusinessList component gets its data from.

I might come back and rework this explanation, as I’m not sure I’ve explained it particularly well… but I’m still grappling with exactly how React works myself. :slight_smile:

1 Like

Thanks a lot for your quick reply. It all sounds very logical.

On top of trying to understand React I am also dealing with a language barrier from English to my native language Dutch.

Should you find your answers needs updating please let me know. But it all sounds pretty good to me.

1 Like