The React onClick
event is one of many “event listeners.” Adding event listeners to React components is one of the most important capabilities of the framework. Event listeners are used to make your application interactive. You can take certain actions when a button is pressed, a form is submitted, or when pretty much anything happens on your components.
Prerequisite Knowledge
- JSX Basics
- JavaScript functions/callbacks
Adding onClick (and other Listeners) to React Components
The capabilities of our first event listeners is going to be limited until we learn about state in a later article. For now we will take simple actions such as logging to the console.
Perhaps you remember that in JSX, all attributes, including inline events, are camelCased. So instead of an onclick
event, we will add a onClick
event. The same applies to all other events: onHover, onMouseOver, onSubmit,
etc.
To add an event handler to an element, we need to embed it as a JavaScript expression, either as a previously defined function or an anonymous function.
Let’s create a simple button component and add an event handler to it.
const InteractiveButton = () => {
const handleSubmit = () => {
alert('SECRET MESSAGE: This component is completely useless. . .');
};
return (
<button onClick={handleClick}>Click to view secret message!</button>
);
};
Event Listeners with State
If you know how to use state in React, there are many more capabilities for your application. You can create listeners for buttons and forms that can update the component state when they are clicked or submitted.
import { useState } from 'react';
const UserInfo = () => {
const [userInfo, setUserInfo] = useState({});
const handleSubmit = (e) => {
const { elements: fields } = e.target;
const newInfo = {
fullName: fields.firstName.value + fields.lastName.value,
age: fields.age.value,
favoriteFood: fields.favoriteFood.value
};
setUserInfo(newInfo);
};
return (<>
<h2>Name: {userInfo.fullName}</h2>
<h2>Age: {userInfo.age}</h2>
<h2>Favorite Food: {userInfo.favoriteFood}</h2>
<form onSubmit={handleSubmit}>
<input type='text' name='firstName' placeholder='First Name' />
<input type='text' name='lastName' placeholder='Last Name' />
<label for='ageInput'>Age:</label>
<input type='number' min='13' max='120' name='age' id='ageInput' />
<input type='text' name='favoriteFood' placeholder='Favorite Food' />
<button type='submit'>Submit</button>
</form>
</>);
};
For simple events, it is okay to use an anonymous function. This is common when you have a button that makes a simple state change. For example, in the ubiquitous Counter example:
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div id='counter'>
<h1>Count: {count}</h1>
<button onClick={() => setCount(prev => prev+ 1)}>Increment Count</button>
</div>
);
};
You can read more on handling events in React in the docs.
In the next article, we’ll learn how to implement conditional rendering in React.