In React, events allow you to make your applications interactive. You can respond to user actions such as clicks, typing, form submissions, mouse movements, and keyboard inputs. React uses a system called Synthetic Events that normalizes events across different browsers to provide a consistent API.
Unlike traditional HTML where event handlers are lowercase and use strings, React events are named using camelCase and you pass a function reference instead of a string. This ensures better performance and allows you to handle events declaratively.
Here, handleClick
is a JavaScript function that runs when the button is clicked. Notice how the event handler is passed directly as onClick={handleClick}
, not as a string.
In many cases, especially with forms and links, you want to prevent the browser's default action. React's synthetic events provide a method called preventDefault()
for this.
The handleSubmit
function calls event.preventDefault()
to stop the form from refreshing the page, which is the default behavior.
Sometimes you need to pass extra data to your event handler. You can do this with arrow functions or Function.prototype.bind
.
Using () => greet(props.name)
ensures the function greet
only runs when the button is clicked, not immediately on render.
React implements event pooling to improve performance, meaning the event object is reused and all properties are nullified after the event callback runs. If you want to use the event asynchronously (e.g., in a timeout or promise), you need to call event.persist()
.
onClick
— mouse click eventsonChange
— input or form element value changeonSubmit
— form submissiononMouseEnter / onMouseLeave
— mouse hover enter/leaveonKeyDown / onKeyUp
— keyboard key pressed or releasedthis
context inside event handlers!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!