Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Building a Search Feature

Function performSearch from parent component is called in child component

Can someone get a general explanation on how a function from App component was passed and linked in the child component? More reading on best practices for such a schema.

1 Answer

Dom McKellar
Dom McKellar
6,052 Points

Remember, it's just JavaScript under the hood. Functions are still objects, therefore, they can be passed as arguments. So rather than passing some primitive value like a string <MyComponent someProp="foo"/> or a number <MyComponent someProp={100}/>, in this case you're simply passing a function as the argument <MyComponent someProp={myFunction}/>. By passing it along as a prop, you're able to both access and invoke it in your child component. Think of it like this:

var myFunction = function() {
  // ...code
}

var childComponent = function(onFunction) {
  onFunction();
  // ...code
}

// React will call it later on in the component lifecycle:
childComponent(myFunction)