-2

The following code uses an arrow function to pass a function parameter through onClick in React;

import React from 'react';

const ExampleComponent = () => {
  
  function sayHello(name) {
    alert(`hello, ${name}`);
  }
  
  return (
    <button onClick={() => sayHello('James')}>Greet</button>
  );
}

export default ExampleComponent;

Why can't I use <button onClick={sayHello('James')}>Greet</button>? It looks simpler.

I'm a total newbie to ReactJS. Please be patient if it is a trivial question.

The code was extracted from the link below. https://upmostly.com/tutorials/pass-a-parameter-through-onclick-in-react

user3848207
  • 2,659
  • 13
  • 40
  • 74
  • 1
    `sayHello('James')` *calls* the function. It isn't a function reference that can be called later. – VLAZ May 30 '22 at 10:18
  • 1
    Without arrow functions you'd have to write `onClick={function () { sayHello('James'); }}` – ChrisG May 30 '22 at 10:19
  • 1
    @ChrisG or `sayHello.bind(null, 'James')` but I personally prefer the arrow function. – VLAZ May 30 '22 at 10:20
  • @VLAZ, thanks for the comment. That's the answer. I need to pass a function reference. The negative votes came first. StackOverflow folks need to be more patient with dumber folks like me. – user3848207 May 30 '22 at 10:24

0 Answers0