Languages
[Edit]
EN

React - onClick with alert

3 points
Created by:
Frida-Timms
667

In this article we would like to show you how to display alert attached to onClick acton in React.

Solution 1 - using inline arrow function

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

// ONLINE-RUNNER:browser;

//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 );

Solution 2 - 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.

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// 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 );
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - onClick with alert
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join