D
D
Dmitry Avilov2020-06-30 20:25:56
React
Dmitry Avilov, 2020-06-30 20:25:56

Why does the onClick property of a button fire on page load and not on click?

Good day.
Why, when using the onClick property, it does not work when the button is pressed, but when the page loads, and nothing happens when the button is pressed (I hang up a regular alert to check) I
5efb756178981019536441.png
use the Material UI library, but even when I change the button to the standard one from React, the effect is like this same.
wtf?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lexiglasses, 2020-06-30
@Avilov01

Try passing a callback to the handler like this:
onClick={() => alert('clicked')}

8
8XL, 2020-06-30
@8XL

The previous two answers are correct, but I will clarify that in your case you are not rendering an event on click, but just an alert, and the correct solution indicated earlier would be to call an anonymous / non-anonymous (this is better) function, which will process the event.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question