Event Handling in React
1. Functional component event handling
<button onClick = {clickNext}> next </button>
In JSX, line 11, when the button gets clicked, the click handler callback function clickNext
will run. The helper function, clickNext
on line 5 will be triggered and the console will print “next button clicked
”.
2. Class component event handling
For React class components, the only difference for the event handling is adding this
before the click handler function.
You can refer to the multiple examples of SyntheticEvent wrapper in this document below.
Event
In order to see all the events that are happening in the handler, you can add the event as an argument in the callback function and log the event in the console as shown in the code and image above.
Comparing to Vanilla JavaScript Event Handling
This React event handling is different from event handling in vanilla JavaScript. The steps are shown below. For event handling in React, you can skip this vanilla JavaScript step 1 and directly add the event listener in the JSX.
- Select the element of the DOM
const swimming = document.getElementById("swimming")
2. Add event listener to the piece
swimming.addEventListner
3. Give callback to event listener (remove, add, etc)
swimming.addEventListener("click", () => {console.log("swimming clicked")})
That’s it. Hope you have a decent understanding of how event handling works in React now. Thank you for reading.
More content at plainenglish.io