0 day streak
javascript / beginner
Snippet

Handling Click Events in Components

To make a component interactive in Next.js, you define a function to handle the event and pass it to the 'onClick' prop. The 'use client' directive is required for interactivity in the App Router.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
"use client";
export default function AlertButton() {
function handleClick() {
alert("Button was clicked!");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
nextjs
Breakdown
1
"use client";
Tells Next.js that this is a Client Component, allowing the use of event listeners.
2
onClick={handleClick}
Attaches the handleClick function to the button's click event.