0 day streak
javascript / beginner
Snippet

Defining Event Handlers as Functions

In React, you pass a function as the event handler rather than a string. This keeps your logic organized and reusable.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
function ActionButton() {
function handleClick() {
alert('Button was clicked!');
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
react
Breakdown
1
function handleClick() { ... }
Defines a local function that contains the logic to run when the event occurs.
2
onClick={handleClick}
Assigns the function to the 'onClick' event. Note that we don't use parentheses here (no 'handleClick()').