JavaScript and React course ยท Module 3: State and Events
Event Handling
In this lesson8
On a cosmic journey through React, event handling is like a flight control system, allowing you to respond to various user actions. It is a key element of creating interactive interfaces that respond to user actions such as clicks, text input, or mouse movements.
Basics of event handling in React
In React, event handling works similarly to standard HTML, but with a few important differences:
Event names use camelCase convention instead of lowercase:
- HTML:
onclick,onmouseover - React:
onClick,onMouseOver
- HTML:
In JSX, we pass a function as the event handler, not a string:
- HTML:
<button onclick="handleClick()">Click</button> - React:
<button onClick={handleClick}>Click</button>
- HTML:
To prevent default behavior, we must explicitly call
preventDefault:- HTML:
<a href="#" onclick="return false">Click</a> - React:
<a href="#" onClick={(e) => e.preventDefault()}>Click</a>
- HTML:
Responding to user actions
Events are how React components respond to user actions. Let's look at the basic event types and how to handle them.
Handling clicks
The simplest and most commonly used event is onClick:
function LaunchButton() {
const handleLaunch = () => {
console.log('Starting the countdown to launch!');
// Rocket launch logic...
};
return (
<button
className="launch-button"
onClick={handleLaunch}
>
Start Countdown
</button>
);
}Arguments in event handlers
Every event handler receives an event object as its first argument. It contains information about the event and offers methods like preventDefault():
function NavigationLink() {
const handleClick = (event) => {
event.preventDefault(); // Prevents the default action (e.g., navigating to another page)
console.log('Link clicked, but the page did not reload');
// Custom navigation or other logic...
};
return (
<a
href="/destination"
onClick={handleClick}
>
Go to Destination
</a>
);
}The object React passes to the handler is a SyntheticEvent - a wrapper around the browser's native event. It has the same interface (target, preventDefault(), stopPropagation()) and works the same way in every browser; the original event is in event.nativeEvent. So the order is: the user clicks, the browser creates the event, React wraps it in a SyntheticEvent, and only then calls your handler.
Passing arguments to event handlers
Sometimes we need to pass additional arguments to an event handler. We can do this in two ways:
1. Using an arrow function
function MissionControl({ missions }) {
const selectMission = (missionId, event) => {
console.log(`Selected mission with ID: ${missionId}`);
console.log('Event:', event);
// Mission selection logic...
};
return (
<div className="mission-control">
<h2>Available Missions</h2>
<ul>
{missions.map(mission => (
<li key={mission.id}>
{mission.name}
<button onClick={(e) => selectMission(mission.id, e)}>
Select
</button>
</li>
))}
</ul>
</div>
);
}2. Using bind
function MissionControl({ missions }) {
const selectMission = (missionId, event) => {
console.log(`Selected mission with ID: ${missionId}`);
// Mission selection logic...
};
return (
<div className="mission-control">
<h2>Available Missions</h2>
<ul>
{missions.map(mission => (
<li key={mission.id}>
{mission.name}
<button onClick={selectMission.bind(null, mission.id)}>
Select
</button>
</li>
))}
</ul>
</div>
);
}The arrow function approach is more common and usually more readable.
Popular events in React
React supports a wide range of events, which can be divided into several categories:
Mouse events
onClick- clickonDoubleClick- double clickonMouseEnter- cursor enters an elementonMouseLeave- cursor leaves an elementonMouseMove- cursor moves over an element
Form events
onChange- change in a form element's valueonSubmit- form submissiononFocus- element receives focusonBlur- element loses focus
Keyboard events
onKeyDown- key pressed downonKeyPress- deprecated, useonKeyDowninsteadonKeyUp- key released
Touch events (for mobile devices)
onTouchStart- touch beginsonTouchMove- movement during touchonTouchEnd- touch ends
Examples of handling different events
Mouse events with state
State remembers whether the cursor is over the panel and whether the panel has been clicked, and the onMouseEnter, onMouseLeave and onClick events only change that state:
function InteractivePanel() {
const [isHovered, setIsHovered] = useState(false);
const [isClicked, setIsClicked] = useState(false);
return (
<div
className={`panel ${isHovered ? 'hovered' : ''} ${isClicked ? 'clicked' : ''}`}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => {
setIsHovered(false);
setIsClicked(false);
}}
onClick={() => setIsClicked(!isClicked)}
>
<h3>Interactive Panel</h3>
<p>
{isHovered ? 'Cursor over panel' : 'Hover over the panel'}
{isClicked ? ' - Panel active' : ' - Click to activate'}
</p>
</div>
);
}Keyboard events
Keys are handled just like clicks - with onKeyDown on an element, and event.key tells you which key was pressed:
function SpaceshipControls() {
const [position, setPosition] = useState({ x: 50, y: 50 });
const handleKeyDown = (event) => {
switch(event.key) {
case 'ArrowUp':
setPosition(prev => ({ ...prev, y: Math.max(0, prev.y - 5) }));
break;
case 'ArrowDown':
setPosition(prev => ({ ...prev, y: Math.min(100, prev.y + 5) }));
break;
case 'ArrowLeft':
setPosition(prev => ({ ...prev, x: Math.max(0, prev.x - 5) }));
break;
case 'ArrowRight':
setPosition(prev => ({ ...prev, x: Math.min(100, prev.x + 5) }));
break;
default:
return;
}
};
return (
<div className="spaceship-simulator" tabIndex={0} onKeyDown={handleKeyDown}>
<h2>Spaceship Simulator</h2>
<p>Click the simulator and steer the ship with the arrow keys</p>
<div className="universe" style={{ position: 'relative', width: '400px', height: '400px', background: 'black' }}>
<div
className="spaceship"
style={{
position: 'absolute',
left: `${position.x}%`,
top: `${position.y}%`,
transform: 'translate(-50%, -50%)',
width: '20px',
height: '20px',
background: 'red'
}}
></div>
</div>
<div className="coordinates">
<p>Position X: {position.x}</p>
<p>Position Y: {position.y}</p>
</div>
</div>
);
}tabIndex={0} lets the div element receive focus, so onKeyDown works once you click the simulator. Listening on the whole document requires useEffect with a cleanup - you will learn it in the module on effects.
Passing functions as props
We often need to pass event handler functions from a parent component to a child component. This is a common practice that enables communication between components:
function MissionControl({ onLaunch, onAbort }) {
const [countdown, setCountdown] = useState(10);
const [isLaunching, setIsLaunching] = useState(false);
// useRef keeps the timer id between renders (changing a ref does not trigger a re-render)
const timerRef = useRef(null);
const stopTimer = () => {
clearInterval(timerRef.current);
timerRef.current = null;
};
const startCountdown = () => {
setIsLaunching(true);
let secondsLeft = 10;
setCountdown(secondsLeft);
timerRef.current = setInterval(() => {
secondsLeft -= 1;
setCountdown(secondsLeft);
if (secondsLeft === 0) {
stopTimer();
setIsLaunching(false);
onLaunch(); // Calling the function from props after the countdown finishes (outside the state updater function)
}
}, 1000);
};
const abortLaunch = () => {
stopTimer(); // Stop the countdown first
setIsLaunching(false);
setCountdown(10);
onAbort(); // Calling the function from props on abort
};
return (
<div className="mission-control">
<h2>Mission Control Center</h2>
<div className="countdown">
{isLaunching
? `Launch in: ${countdown}`
: 'Ready for launch'}
</div>
<div className="control-buttons">
{!isLaunching ? (
<button onClick={startCountdown}>Start Countdown</button>
) : (
<button onClick={abortLaunch} className="abort">Abort Launch</button>
)}
</div>
</div>
);
}
// Using the component
function SpaceProgram() {
const handleLaunch = () => {
console.log('Rocket has launched!');
// Post-launch logic...
};
const handleAbort = () => {
console.log('Launch aborted!');
// Post-abort logic...
};
return (
<div className="space-program">
<h1>Space Program</h1>
<MissionControl
onLaunch={handleLaunch}
onAbort={handleAbort}
/>
</div>
);
}The function passed to setState (a functional update) must be pure: in development mode (StrictMode) React calls it twice, so calling onLaunch() inside it would launch the rocket twice. That is why we count the seconds in a plain secondsLeft variable and call onLaunch() and onAbort() directly in the timer and handler code. The timer id is kept in useRef so that abortLaunch can stop it - you will learn more about useRef with uncontrolled components in the lesson on data flow.
Form handling
Forms are a key element of user interaction in web applications. React offers two approaches to form handling: controlled and uncontrolled components.
Controlled forms
In controlled components, form data is controlled by React state:
function MissionSetup() {
const [missionData, setMissionData] = useState({
name: '',
destination: 'Moon',
crew: 3,
duration: 7
});
const handleChange = (e) => {
const { name, value } = e.target;
setMissionData({
...missionData,
[name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Mission data:', missionData);
// Data submission logic...
};
return (
<div className="mission-setup">
<h2>Mission Configuration</h2>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Mission Name:</label>
<input
type="text"
id="name"
name="name"
value={missionData.name}
onChange={handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="destination">Destination:</label>
<select
id="destination"
name="destination"
value={missionData.destination}
onChange={handleChange}
>
<option value="Moon">Moon</option>
<option value="Mars">Mars</option>
<option value="ISS">International Space Station</option>
<option value="Asteroid">Asteroid Belt</option>
</select>
</div>
<div className="form-group">
<label htmlFor="crew">Number of Crew Members:</label>
<input
type="number"
id="crew"
name="crew"
min="1"
max="10"
value={missionData.crew}
onChange={handleChange}
/>
</div>
<div className="form-group">
<label htmlFor="duration">Duration (days):</label>
<input
type="number"
id="duration"
name="duration"
min="1"
value={missionData.duration}
onChange={handleChange}
/>
</div>
<button type="submit">Plan Mission</button>
</form>
</div>
);
}In the example above:
- Each form field has a corresponding entry in the state
- The value of each field is controlled by state
- The
onChangeevent updates the state, which in turn updates the field value - The
onSubmitevent is used to handle form submission
Handling multiple form field types
Different form fields require slightly different approaches:
function AstronautRegistration() {
const [formData, setFormData] = useState({
name: '',
age: '',
specialty: 'pilot',
experience: '',
isTrainee: false,
bio: '',
preferredShift: 'morning'
});
const handleChange = (e) => {
const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
setFormData({
...formData,
[e.target.name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Astronaut data:', formData);
// Registration logic...
};
return (
<div className="astronaut-registration">
<h2>Astronaut Registration</h2>
<form onSubmit={handleSubmit}>
{/* Text input */}
<div className="form-group">
<label htmlFor="name">Full Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
{/* Number input */}
<div className="form-group">
<label htmlFor="age">Age:</label>
<input
type="number"
id="age"
name="age"
value={formData.age}
onChange={handleChange}
required
/>
</div>
{/* Select */}
<div className="form-group">
<label htmlFor="specialty">Specialty:</label>
<select
id="specialty"
name="specialty"
value={formData.specialty}
onChange={handleChange}
>
<option value="pilot">Pilot</option>
<option value="engineer">Engineer</option>
<option value="scientist">Scientist</option>
<option value="doctor">Doctor</option>
</select>
</div>
{/* Radio buttons */}
<div className="form-group">
<p>Preferred Shift:</p>
<label>
<input
type="radio"
name="preferredShift"
value="morning"
checked={formData.preferredShift === 'morning'}
onChange={handleChange}
/>
Morning
</label>
<label>
<input
type="radio"
name="preferredShift"
value="evening"
checked={formData.preferredShift === 'evening'}
onChange={handleChange}
/>
Evening
</label>
</div>
{/* Checkbox */}
<div className="form-group">
<label>
<input
type="checkbox"
name="isTrainee"
checked={formData.isTrainee}
onChange={handleChange}
/>
Trainee Status
</label>
</div>
{/* Textarea */}
<div className="form-group">
<label htmlFor="bio">Biography:</label>
<textarea
id="bio"
name="bio"
value={formData.bio}
onChange={handleChange}
rows="4"
></textarea>
</div>
{/* Range */}
<div className="form-group">
<label htmlFor="experience">Years of Experience: {formData.experience}</label>
<input
type="range"
id="experience"
name="experience"
min="0"
max="30"
value={formData.experience}
onChange={handleChange}
/>
</div>
<button type="submit">Register</button>
</form>
</div>
);
}Error handling and form validation
In real-world applications, it is important to validate user input:
function MissionPlanner() {
const [formData, setFormData] = useState({
missionName: '',
launchDate: '',
budget: ''
});
const [errors, setErrors] = useState({});
const validateForm = () => {
const newErrors = {};
// Mission name validation
if (!formData.missionName.trim()) {
newErrors.missionName = 'Mission name is required';
} else if (formData.missionName.length < 3) {
newErrors.missionName = 'Mission name must be at least 3 characters';
}
// Launch date validation
if (!formData.launchDate) {
newErrors.launchDate = 'Launch date is required';
} else {
const selectedDate = new Date(formData.launchDate);
const today = new Date();
if (selectedDate <= today) {
newErrors.launchDate = 'Launch date must be in the future';
}
}
// Budget validation
if (!formData.budget) {
newErrors.budget = 'Budget is required';
} else if (isNaN(formData.budget) || Number(formData.budget) <= 0) {
newErrors.budget = 'Budget must be a positive number';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0; // Form is valid if there are no errors
};
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
// Clear error for the field being changed
if (errors[name]) {
setErrors({
...errors,
[name]: undefined
});
}
};
const handleSubmit = (e) => {
e.preventDefault();
if (validateForm()) {
console.log('Mission data submitted:', formData);
// Data submission logic...
} else {
console.log('Form contains errors');
}
};
return (
<div className="mission-planner">
<h2>Space Mission Planning</h2>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="missionName">Mission Name:</label>
<input
type="text"
id="missionName"
name="missionName"
value={formData.missionName}
onChange={handleChange}
className={errors.missionName ? 'error' : ''}
/>
{errors.missionName && <div className="error-message">{errors.missionName}</div>}
</div>
<div className="form-group">
<label htmlFor="launchDate">Launch Date:</label>
<input
type="date"
id="launchDate"
name="launchDate"
value={formData.launchDate}
onChange={handleChange}
className={errors.launchDate ? 'error' : ''}
/>
{errors.launchDate && <div className="error-message">{errors.launchDate}</div>}
</div>
<div className="form-group">
<label htmlFor="budget">Budget (in millions $):</label>
<input
type="number"
id="budget"
name="budget"
value={formData.budget}
onChange={handleChange}
className={errors.budget ? 'error' : ''}
/>
{errors.budget && <div className="error-message">{errors.budget}</div>}
</div>
<button type="submit">Plan Mission</button>
</form>
</div>
);
}Summary
Event handling is a key element of creating interactive applications in React. Thanks to it, we can:
- Respond to user actions such as clicks, mouse movement, or text input
- Update component state based on interactions
- Communicate between components by passing functions as props
- Handle forms and validate user input
Proper event handling, combined with state management, allows you to create dynamic, responsive user interfaces that provide users with an intuitive experience.
Code for this lesson: App.jsx
import React, { useState } from 'react';
function EventDemo() {
const [clickCount, setClickCount] = useState(0);
const [inputText, setInputText] = useState('');
const [isHovered, setIsHovered] = useState(false);
const [selectedOption, setSelectedOption] = useState('Mars');
const handleButtonClick = () => {
setClickCount(clickCount + 1);
};
const handleInputChange = (event) => {
setInputText(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Form submitted with text: "${inputText}"`);
};
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
alert('Enter pressed!');
}
};
return (
<div className="event-demo">
<h1>React Event Handling Demo</h1>
<div className="demo-section">
<h2>Mouse Events</h2>
<button
onClick={handleButtonClick}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
className={isHovered ? 'hovered' : ''}
>
Click me! (Clicked: {clickCount} times)
</button>
</div>
<div className="demo-section">
<h2>Form Events</h2>
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputText}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
placeholder="Type text and press Enter or submit the form"
/>
<select
value={selectedOption}
onChange={(e) => setSelectedOption(e.target.value)}
>
<option value="Mars">Mars</option>
<option value="Moon">Moon</option>
<option value="Venus">Venus</option>
<option value="Jupiter">Jupiter</option>
</select>
<button type="submit">Submit form</button>
</form>
<div className="output">
<p>Current text: {inputText}</p>
<p>Selected option: {selectedOption}</p>
</div>
</div>
<div className="demo-section">
<h2>Touch and Interaction Events</h2>
<div
className="interactive-area"
onTouchStart={() => console.log('Touch started')}
onTouchEnd={() => console.log('Touch ended')}
onDoubleClick={() => alert('Double click!')}
>
Double-click or tap (check the console)
</div>
</div>
</div>
);
}
function App() {
return (
<div className="app">
<EventDemo />
</div>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Horizontal ordering
Arrange the correct syntax for updating state using the previous value:
- Code editor
Create an oxygen counter: const [oxygen, setOxygen] = useState(21). Display the text O2 Level: {oxygen}% and add two buttons: the + button raises the level by 1 (<button onClick={() => setOxygen(prev => prev + 1)}>+</button>) and the - button lowers it by 1. The level must stay within 0-100.
- Click in order
Build the correct click handler attribute in JSX:
- Click in order
Arrange the process of using useState: