React is a free, open-source javascript library used for building user interfaces by splitting them up into multiple individual components.
An event handler is a function responsible for handling events. It can be triggered by a website user clicking on a button or specific keyboard key combinations.
Using event handlers, we can define custom behavior that should occur when an event is initiated. In React, event handlers are attached to specific components using event props that are named after DOM elements.
Below we can see an App
component that renders a button that, when clicked, does nothing.
Now we will add an event handler to this button such that when the button is clicked, it gives a "Hello World" alert.
To do so, we would need to follow the steps below:
Create a function that should give an alert of "Hello World" when the function is called.
Bind the function to the button so the alert function is called whenever the button is clicked.
In the code block above, we first create a handleClick()
function and then bind the function to the button. When the button is pressed, the handleClick()
function is called. Over here, the handleClick()
function is the event handler.
Note: It is prefered to start the name of event handlers with
handle
followed by the name of the event that is to be handled, eg.handleButtonClick
As event handlers are functions that are declared inside a React component, they have access to the props associated with the component.
Below is a sample react application in which an event handler uses a component prop element.
Below is a brief explanation of the code shown above.
Lines 2–10: We create an AlertButton
React component that takes a message prop.
Lines 4–8: Render a button with an onClick
event handler that displays the message prop as an alert.
Lines 14–17: Render the AlertButton
component and send "Hello World" to it as a message prop.
In HTML, the <div>
, <button>
and <form>
elements only support predefined event names. However, if we are building our own components, we can assign custom names to their event handler props.
In the example below, we can see an AlertButton
component that uses a custom name event handler prop called onPush,
which clicked sends an alert "Button Pushed" to the client's browser.
Following is a brief explanation of the code:
Lines 1–7: Create an AlertButton
component that takes onPush
as a prop and binds it to the onClick of a button.
Lines 12–13: We render an AlertButton
component and pass it a "Hello World" alert arrow function as a onPush
event handler prop.