React Event Handling: A Beginner’s Guide

Event handlers are functions that will be triggered in response to certain user actions, such as clicking a button, submitting a form, moving the mouse, typing in a text field, and so on.

For instance, consider the following example. Run the CodePen demo and click the button that says Click me. An alert box should pop up.

Open demo in new tab
html
1<button onclick="success()">Click me</button>

In this case, we are using the onclick attribute to set up an event handler for the <button> element. When the button is clicked, the corresponding success() function will be executed.

This code should look familiar to you, because it is the same example we used in the JavaScript Event Handling lesson.

Creating an event handler

We can do the same thing for JSX. Except, as we've mentioned before, the attributes in JSX should be written in camelCase, which means instead of onclick, you need to use onClick.

Button.jsx

jsx
1function Button() {
2  function handleClick() {
3    alert("Hello, World!");
4  }
5  return <button onClick={handleClick}>Click me</button>;
6}
7
8export default Button;

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉