BeginnerCoder

Lesson 9 — Handling events

One handler, many buttons

An event handler is the function React calls when something happens, such as a click. It receives the event object: e.target is the element that was clicked, so e.target.textContent is its text. One handler can therefore serve many buttons.

function handle(e) {
  console.log("clicked", e.target.textContent);
}
<button onClick={handle}>Save</button>

Pass the function itself (onClick={handle}), not a call (onClick={handle()}), or it runs immediately.

Why it matters: menus, tabs and toolbars share handlers like this instead of repeating code.

Want it another way?
Task

Save the clicked button's text in last. Clicking Pears should show "You picked: Pears".

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.