Passing Method reference between Components in React

In the previous post we used event handler to change the state and change the information shown on UI, now Lets say we want to make that change not only with the button click event, but also by clicking anywhere on the paragraph element.

For that we will add onClick to the paragraph like we did with button element.
App.js

So we may think that we can do the same with paragraph from UI like below:
Employee.js

But there is a problem we cannot call handler into another file. So the solution is to pass the reference of event handler method to our component as a property.

We will introduce new property(props) clickParagraph and that props will carry a reference to our event handler method. Then this props will be available to access in Employee.js

App.js

Employee.js

The property that we introduced in App.js is now accessible in Employee.js like below

Now whenever you click on the paragraph, the text in a paragraph will get changed.

Conclusion

  • You cannot pass handlers down to the child component(Employee.js) which allow you to change data in the parent component(App.js) 
  • You can pass methods, props. So that you can call a method which changes state in another component which doesn’t have direct access to the state.