Types of Event Listeners in React (Quick-Read)

Unlike vanilla JavaScript where addEventListener is used to add event listeners to the DOM element after the element is created, React makes it easier. Simply add a listener when the element is initially rendered, like-so:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
As you can see onClick={handleClick}
calls on the above function handleClick
and console.log
’s: ‘The link was clicked’.
Some of the many types of event listeners in React include:
Keyboard Events:
onKeyDown
— Called when a key is depressed
onKeyPress
— Called after a key is released (before onKeyUp
is triggered)
onKeyUp
— Called last, after a key is pressed
You can also check if a modifier key was pressed at the time of an event with these properties (each are booleans):
altKey
ctrlKey
metaKey
shiftKey
Form Events:
onChange
— Called when the user changes value in form control
onSubmit
— Called when submit
button or return is pressed
Mouse Events:
onClick
— A mouse button was pressed and released (called before onMouseUp
)
onMouseDown
— A mouse button was depressed
onMouseUp
— A mouse button was released
onContextMenu
— The right mouse button was pressed
onDoubleClick
— Triggered by double click
onMouseEnter
— Mouse moves over an element
onMouseLeave
— Mouse leaves an element
onMouseOver
— Mouse moves directly over an element