Just like in vanilla JavaScript, React let’s you add event listeners or event handlers wherein if you hover on something or click something, then something else will be triggered. For example, you can write a JSX code in React where if you click a button, a pop-up message displays.
Here’s how to add a simple event handler in React JSX :
function clickHereButton() {
function myMessage() {
alert("Surprise!!!!");
}
return <button onClick={myMessage}>Click Here</button>;
}
export default clickHereButton;
We’ve created a button and added an onClick event listener which takes in myMessage function as the parameter which eventually shows a popup.
Here’s how it looks like :
So, in the above animation, when you click on the button a popup message appears.
Alternatively, you can add the same event handler functionality above, a bit differently as shown below (the result remains the same):
function clickHereButton() {
return (
<button
onClick={function myMessage() {
alert("Surprise!!!");
}}
>
Click Here
</button>
);
}
export default clickHereButton;
What’s happening above is that the popup is triggered right inside the onClick event as an inline function, which also works the same way.
You could also use an arrow function instead. This is how it works inside React :
function clickHereButton() {
return (
<button
onClick={() => {
alert("Surprise!!!");
}}
>
Click Here
</button>
);
}
export default clickHereButton;
There’s many other events like onChange, onInput and onSubmit which can be used as other options. Another example with onSubmit event is given below :
export default function SendMessage() {
return (
<div>
<h3>Message:</h3>
<form onSubmit={() => alert("Message Sent!")}>
<input />
<button>Send</button>
</form>
</div>
);
}
Here’s the output :