-2

If I open a new codesandbox template for react, and have it return a simple button like the following

<button onClick={alert('hello world')}>click</button>

The onClick event alert message fires only upon first render, and does not fire upon clicking the button.

Why doesnt it fire when clicking the button, and how can I modify my code so that it does?

draca
  • 1,319
  • 5
  • 16
  • 32
  • Does this answer your question? [React onClick function fires on render](https://stackoverflow.com/questions/33846682/react-onclick-function-fires-on-render) – Rafael Tavares Jan 18 '22 at 12:51
  • bind the value to the function: since it's a function you can use arrow function for binding onClick{()=>alert........} – Borni.Mr Jan 18 '22 at 12:58

4 Answers4

-1

onClick should be assigned with a function

<button onClick={()=>alert('hello world')}>click</button>
Eliav Louski
  • 3,593
  • 2
  • 28
  • 52
-1

onClick attribute is purely JavaScript. The value it takes, which is the function you want to execute.

  <button onClick={() => alert('hello world')}>Click</button>

basic onClick syntax

  <element onClick="functionToExecute()">Click</element>
Onkar Kole
  • 1,197
  • 7
  • 13
-1

You should do

<button onClick={()=> alert("Hello world")}>click</button>
hamid saifi
  • 184
  • 2
  • 3
-1

1. First Soltioun

using inline arrow function In below example alert is placed inside arrow function assigned directly to the button's onClick property.

//Note: Uncomment import lines during working with JSX Compiler.
// import React from react';
// import ReactDOM from react-dom';

const App = () => {
    return (
      <div >
        <button onClick={() => alert('button click catched')}>Click me</button>
      </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

2. Second solution

using event handling function In below example we create external handleClick arrow function which displays an alert. Then we pass handleClick function to the button's onClick property which handles mouse click event.

    // import React from react';
// import ReactDOM from react-dom';

const handleClick = () => {
    alert('button click catched');
};

const App = () => {
    return (
      <div >
        <button onClick={handleClick}>Click me</button>
      </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
nermineslimane
  • 541
  • 4
  • 21