2

I understand that this is not the right way to make a button show an alert on click.

I would like to understart the logic behind this. I understand that on click needs to get a reference to a function in order to function as expected.

In the following example, a reference is being made to an arrow function which will be called on click:

<button onClick={() => alert('hi)}>Click me!</button>

But what happens behind the scenes in this case:

<button onClick={alert('hi)}>Click me!</button>

Why is the statement inside onClick being evaluated at render?

Edit: I am using React.

Weedoze
  • 13,683
  • 1
  • 33
  • 63
  • 2
    Are you using a template framework? What are the `{}` for? – Barmar Jan 23 '18 at 10:18
  • 1
    Yes, probably a framework that evaluates the stuff between {} at parse time. Just use plain JavaScript `onclick="alert('hi')"` and the problem will go away. However, if you're really asking "How can I prevent whatever framework I'm using from showing an alert at parse time while using {}", then maybe you should rephrase the question. – Mr Lister Jan 23 '18 at 10:20
  • This for your replies. Edited the question. I'm using React. –  Jan 23 '18 at 10:38

2 Answers2

5

Imagine you have a method like so:

function getString(){

   return "string";
}

and then define a textbox:

<input type="text" value={getString()}/>

You would expect that the textbox would be rendered with a value of "string" not "getString()". This is because what is within the curly braces is evaluated in the render method.

When {alert('hi)} is evaluated it runs the method so what is assigned to the onclick event is what is returned by alert('hi') (nothing) not the method itself.

SBFrancies
  • 3,987
  • 2
  • 14
  • 37
2

In react application, we write html in javascript and not in HTML.

So at the time of rendering, javascript will execute this function: alert('hi')

By using this syntax:

 <button onClick={() => alert('hi')}>Click me!</button>

we are passing function reference to on click. Inner block of this function will only be executed when this event is called.

Shrey Kejriwal
  • 726
  • 4
  • 13