🎓 A1Learner
🔍
0 of 50 lessons completed

Passing Arguments to Handlers

Passing arguments to a handler is a way to give a handler extra values. An arrow function wraps the call and supplies the values.

Pass a string

The arrow function calls greet with Sam.

<button onClick={() => greet('Sam')}>Greet Sam</button>

Define the handler

greet takes a name and logs a greeting.

function greet(name) {
  console.log('Hello ' + name);
}

Pass a number

The handler receives 25 when the button is clicked.

<button onClick={() => showAge(25)}>Show age</button>

Example

function greet(name) {
  console.log('Hello ' + name);
}

export default function App() {
  return (
    <div>
      <button onClick={() => greet('Sam')}>Greet Sam</button>
      <button onClick={() => greet('Mia')}>Greet Mia</button>
    </div>
  );
}

Key points

  • A handler receives the event object by default.
  • An arrow function can call the handler with extra values.
  • The arrow function runs only when the event happens.
  • The value can be a string, a number, or any other value.
  • The arrow function can also pass the event along to the handler.

In this example, greet accepts a name and prints a hello. App returns two buttons. Each button wraps its greet call in an arrow function. A click on Greet Sam calls greet with Sam. The console shows Hello Sam. A click on Greet Mia calls greet with Mia. The console shows Hello Mia.

Note

onClick={greet('Sam')} calls greet during render, so wrap the call in an arrow function.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How do you pass Sam to greet when a button is clicked?