EN
React - onClick with alert
3
points
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 );