0
0
NextJSframework~5 mins

Event handlers in client components in NextJS

Choose your learning style9 modes available
Introduction

Event handlers let your app respond when users click, type, or interact. They make your page feel alive and interactive.

When you want to run code after a user clicks a button.
When you need to update the screen after typing in a form.
When you want to show or hide parts of the page based on user actions.
When you want to handle keyboard presses for accessibility.
When you want to track user interactions for feedback or analytics.
Syntax
NextJS
function MyComponent() {
  function handleClick(event) {
    // code to run on click
  }

  return (
    <button onClick={handleClick}>Click me</button>
  )
}

Use camelCase for event names like onClick, onChange, etc.

Pass a function reference, not a function call, to the event handler.

Examples
Simple click handler that shows an alert.
NextJS
function MyComponent() {
  function handleClick() {
    alert('Button clicked!')
  }

  return <button onClick={handleClick}>Click me</button>
}
Click handler that updates a counter displayed on the button.
NextJS
function MyComponent() {
  const [count, setCount] = React.useState(0)

  function increment() {
    setCount(count + 1)
  }

  return <button onClick={increment}>Clicked {count} times</button>
}
Input change handler that logs the current input value.
NextJS
function MyComponent() {
  function handleInputChange(event) {
    console.log('Input value:', event.target.value)
  }

  return <input type="text" onChange={handleInputChange} aria-label="Name input" />
}
Sample Program

This component shows a button that counts how many times you click it. Each click updates the number shown on the button.

It uses React's useState hook to keep track of the count and an onClick event handler to update it.

The button has an aria-label for accessibility, so screen readers can describe it properly.

NextJS
'use client';

import React, { useState } from 'react'

export default function ClickCounter() {
  const [count, setCount] = useState(0)

  function handleClick() {
    setCount(count + 1)
  }

  return (
    <main style={{ padding: '1rem', fontFamily: 'Arial, sans-serif' }}>
      <button onClick={handleClick} aria-label="Increment counter" style={{ fontSize: '1.25rem', padding: '0.5rem 1rem' }}>
        Clicked {count} times
      </button>
    </main>
  )
}
OutputSuccess
Important Notes

Always use aria-label or visible text for buttons to help screen readers.

Event handlers receive an event object with useful info like which key was pressed or the target element.

Keep event handler functions small and focused for easier debugging.

Summary

Event handlers let your app respond to user actions like clicks and typing.

Use camelCase event names and pass function references in JSX.

React's useState works well with event handlers to update UI dynamically.