How to pass event handler functions in React?
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?
Answer
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM