Event handling
basic event handling in react
Rifki ahmad fahrezi
Introduction
Event handling is the most fundamental understanding to make you website more interactive, even though you’re not using any frontend framework.
On this article we’re not going deep about event handling, but this article will cover a basic introduction of event handling in React, including how to:
- Create an event
- Passing an event handler as props
Create an event
To create an event in React, you just have to attach the event name to the element that will fire it, this is the example for event handling in React on a button element
Passing an event handler as props
Passing an event handler as a props is a common practice is React, by passing an event handler as props you can make your component more reuseable.
For example we’re going to make Button component that can accept an onClick
event that will show an alert dialog with text halo my name is ...
****(the dots will replace to name variable from an arguments), here is the code
Button.jsx
Explanation
-
Add props
handler
to send the event handler function to the button elementButton({ handler })
-
Attach the
handler
props to theonClick
event<button onClick={handler} >
By following this code you can make your button element can accept an event handler to the children element, example usage to the parent component
Result
Handling multiple events
If you want to handle alot of events in your single element on component you use the rest parameter to the props, here is the example
By using rest parameter, not only event handler but the rest of elements attributes like id, className, etc. you can also pass it to the props component, here is the result