Languages
[Edit]
EN

React - onClick with alert

3 points
Created by:
Dirask Community
6810

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

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