How to pass event handler functions in React?

- 1 answer

Ad

I am new in React, and I am still kinda trying to figure out best practices so bear with me.

So, say I have a <ParentComponent /> and a <ChildComponent /> and I want the following behaviour: When the child is clicked, something should happen.

How should I implement the onClick event handler for the <ChildComponent /> ?

Should I define it inside the <ParentComponent />'s class and pass it down to the <ChildComponent />as a prop to use as onClick={this.props.handleClick}or should I define it in the <ChildComponent /> and simply use it with onClick={this.handleClick} ?

Is one method preferred over the other or there is no difference between doing either?

Ad

Answer

Ad

It depends entirely on what the method actually does. If the method is using or altering state in the parent component, then define it in the parent component and pass it down as props. If the method doesn't have anything to do with the parent component or its state, just define it in the child component.

Ad
source: stackoverflow.com
Ad