Handling events
Let's build a simple button that does nothing besides logging to console:
clicker
1
import React, {MouseEvent} from 'react'
2
3
const Clicker: React.FC = () => {
4
const handleButtonClick = (event: MouseEvent<HTMLElement>) => {
5
console.log(event.currentTarget.textContent)
6
}
7
8
return (
9
<button onClick={handleButtonClick}>Click me!</button>
10
)
11
}
Copied!
In React, all event listeners are attached to an element via onEventName property. This is similar to veeery old school JavaScript, but uses camelCase.

Pass, not call

It's important to remember that we are passing the callback as a prop, not calling it:
1
<button onClick={handleButtonClick()}>Click me!</button>
Copied!
As long as we don't intent to call this function each time a component is rerendered.

Fake event

The event received in the callback is slightly different than expected. For starters, it's imported from React instead of just being in global namespace. In fact, it's an instance of the Synthetic Event - this is quite important for React internals, but for us it's just there to avoid a gotcha moment.

Resources