React Events
Learn how React responds to clicks, typing, form submission, pointer movement, focus, and keyboard actions — using small CSE-friendly examples and interactive demonstrations.
Project Setup
The source uses Vite for current React practice. It also notes that older material may show Create React App and older ReactDOM examples.
npm create vite@latest react-events-lab -- --template react cd react-events-lab npm install npm run dev
Tools
VS Code, Node.js LTS and a modern browser.
Browser tools
Open Developer Tools with F12 or Ctrl+Shift+I, then use the Console when an example uses console.log.
1. What is an Event?
An event is an action or occurrence performed by a user for which a program can respond.
Click
A student clicks a button.
Typing
A learner types into a search box.
Form
A student submits a form.
Pointer / Keyboard
The pointer moves or a key is pressed.
onClick or onChange. The component declares the response instead of manually attaching DOM listeners.<button onClick={handleClick}>Mark present</button>
<input onChange={handleChange} />
<form onSubmit={handleSubmit}>...</form>2. Syntax for React Events
React event names use camelCase, unlike HTML’s lowercase event attributes.
| Use this in React | Not this HTML-style spelling |
|---|---|
onClick | onclick |
onMouseEnter | onmouseenter |
onKeyDown | onkeydown |
function handleClick(event) {
console.log(event.type);
}
<button type="button" onClick={handleClick}>Save</button>3. Event Handlers
Named handlers inside a component
export default function App() {
function downloadNotes() {
console.log('Notes download started');
}
function openHelp() {
console.log('Help opened');
}
return (
<>
<button onClick={downloadNotes}>Download notes</button>
<button onClick={openHelp}>Open help</button>
</>
);
}Each button can have its own named handler.
Interactive notice: multiple event types
Interactive notice
Move over or focus the card
import { useState } from 'react';
export default function App() {
const [status, setStatus] = useState('Move over or focus the card');
return (
<article
tabIndex="0"
onMouseEnter={() => setStatus('Pointer entered')}
onFocus={() => setStatus('Card focused')}
onKeyDown={e => setStatus(`Key: ${e.key}`)}
>
<h2>Interactive notice</h2>
<p>{status}</p>
</article>
);
}4. The Event Object
React passes an event object to a handler when an event occurs. It contains useful information about what happened.
event.type
The event type, such as change or click.
event.target
The element that actually triggered the event.
event.currentTarget
The element whose handler is currently running.
event.key
The key value for keyboard events.
event.target.value
The current text/value for form inputs.
Try target vs currentTarget
export default function App() {
function handleClick(event) {
console.log('target:', event.target.tagName);
console.log('currentTarget:', event.currentTarget.tagName);
}
return (
<section onClick={handleClick}>
<button>Click nested button</button>
</section>
);
}Keyboard information
function handleKeyDown(event) {
if (event.key === 'Enter') {
setMessage('Search submitted with Enter');
}
}5. Common React Events
React supports the major browser event categories used in web applications.
| Event prop | Typical element | Use |
|---|---|---|
onClick | button, links, controls | A user activates a control. |
onChange | input, select, textarea | A form value changes. |
onSubmit | form | A form is submitted. |
onKeyDown | input, document-like controls | A key is pressed. |
onFocus / onBlur | form controls | Focus enters or leaves. |
onMouseEnter / onMouseLeave | interactive regions | Pointer enters or leaves. |
6. Mouse Enter, Focus & Blur
Mouse enter and leave
Web Lab
Move the pointer here
export default function App() {
const [hint, setHint] = useState('');
return (
<article
onMouseEnter={() => setHint('React lab begins at 10 AM')}
onMouseLeave={() => setHint('')}
>
<h2>Web lab</h2>
<p>{hint || 'Move the pointer here'}</p>
</article>
);
}Focus and blur validation
const [error, setError] = useState('');
<input
id="email"
onBlur={e =>
setError(
e.target.value.includes('@')
? ''
: 'Enter a valid email'
)
}
/>@ for a dot: e.target.value.includes('@') && e.target.value.split('@')[1]?.includes('.').7. Event Propagation & preventDefault
In bubbling, an event starts at the target and then moves upward through ancestors, so both a button and its parent may respond.
stopPropagation()
Use it when the parent must not receive the event from the inner control.
preventDefault()
Use it when React should manage an action instead of allowing the browser's default action.
Propagation demo
Click the card to open it. The inner button can stop the event from reaching the card.
function openCard() {
alert('Card opened');
}
function addBookmark(event) {
event.stopPropagation();
alert('Bookmarked');
}
return (
<article onClick={openCard}>
<h2>React Foundations</h2>
<button onClick={addBookmark}>Bookmark</button>
</article>
);Prevent a form reload
function handleSubmit(event) {
event.preventDefault();
setNotice('Notice submitted without reloading the page');
}type="button" for non-submit buttons.8. Passing Data to Handlers
Sometimes a handler needs an extra value such as a student ID, product ID or assignment ID. Use an arrow wrapper or bind to pass that value. Do not invoke the handler during rendering.
<button onClick={() => deleteItem(item.id)}>Delete</button>
<button onClick={handleDelete.bind(null, item.id)}>Delete</button>Interactive assignment list
const assignments = [
{ id: 1, title: 'JS basics' },
{ id: 2, title: 'React lab' }
];
function selectAssignment(id) {
setSelected(`Assignment ${id} selected`);
}
{assignments.map(item => (
<li key={item.id}>
{item.title}
<button onClick={() => selectAssignment(item.id)}>Select</button>
</li>
))}9. Events in Function Components & Controlled Inputs
Function components define event handlers as ordinary JavaScript functions inside the component. They can read props, call state setters and use the event object.
import { useState } from 'react';
function App() {
const [query, setQuery] = useState('');
function handleChange(event) {
setQuery(event.target.value);
}
return (
<>
<label htmlFor="q">Search</label>
<input id="q" value={query} onChange={handleChange} />
<p>Searching for: {query || 'all students'}</p>
</>
);
}
export default App;10. Events in Class Components
Class components handle events through methods. A method passed directly to a child can lose its this context because it may be invoked as a plain function.
Class handler with bind
import { Component } from 'react';
export default class App extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(previous => ({
count: previous.count + 1
}));
}
render() {
return (
<>
<p>Clicks: {this.state.count}</p>
<button onClick={this.handleClick}>Add click</button>
</>
);
}
}Bind-style class counter
Class-field arrow handler
import { Component } from 'react';
export default class App extends Component {
state = { status: 'Waiting' };
handleClick = () => {
this.setState({ status: 'Submitted' });
};
render() {
return (
<>
<p>{this.state.status}</p>
<button onClick={this.handleClick}>Submit</button>
</>
);
}
}Class-field arrow demo
Source Visual References
The uploaded document contains screenshots illustrating browser-console output and small event examples. They are preserved here as visual references.
11. Quick Check
event.target identify?
Quick Revision
Event
An action or occurrence that a program can respond to.
Handler
A function React calls when the event occurs.
Event object
Carries details such as type, target, key and form values.
Propagation
Bubbling lets the event move from target to ancestors.
preventDefault()
Stops the browser's default action when React should handle it.
stopPropagation()
Stops the event from reaching an ancestor handler.