Event handlers allow users interact with our website and do something when a certain event such as a click or a hover happens.
To add an event handler to a React Element, assign the event handler method to the appropriate event attribute.
<button onClick={() => console.log("I was clicked!")}>Click me</button>
We can also use a seperate function:
import React from "react"
function handleClick() {
console.log("I was clicked")
}
function App() {
return (
<div>
<h2>Hello</h2>
<button onClick={handleClick}>Click me</button>
</div>
)
}
export default App
React supports several events:
onCopy onCut onPaste
onCompositionEnd onCompositionStart onCompositionUpdate
onKeyDown onKeyPress onKeyUp
onFocus onBlur
onChange onInput onInvalid onReset onSubmit
onError onLoad
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp
onPointerDown onPointerMove onPointerUp onPointerCancel onGotPointerCapture
onLostPointerCapture onPointerEnter onPointerLeave onPointerOver onPointerOut
onSelect
onTouchCancel onTouchEnd onTouchMove onTouchStart
onScroll
onWheel
onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted
onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay
onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend
onTimeUpdate onVolumeChange onWaiting
onLoad onError
onAnimationStart onAnimationEnd onAnimationIteration
onTransitionEnd
onToggle
Read more: React documentation on supported events