🎓 A1Learner
🔍
0 of 50 lessons completed

Handling Events

Handling events means running a function when something happens. An event is an action like a click on a button.

Define a handler

sayHello is a plain function.

function sayHello() {
  console.log("Hello!")
}

Attach the handler

The button shows before any click.

<button onClick={sayHello}>Say hello</button>

The handler waits

Nothing runs until the button is clicked.

onClick={sayHello}

Example

function sayHello() {
  console.log("Hello!")
}
export default function App() {
  return <button onClick={sayHello}>Say hello</button>
}

Key points

  • An event handler is a plain function.
  • The handler runs only when the event happens.
  • onClick names the click event on an element.
  • onClick receives the function name, not a function call.

In this example, sayHello writes Hello! to the console. App returns a button with onClick set to sayHello. The page shows the button. A click runs sayHello. The click does not change the page.

Note

The page shows the button before any click. A click only runs the function.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does onClick={sayHello} do?