../courses.php
React
REACT104
90
Events
Respond when a user clicks, types, submits, or changes something.
How does React respond to user actions?
React uses event handlers such as onClick, onChange, and onSubmit to run code when a user interacts with the interface.
State lets a component remember changing information.
Events are what usually cause that information to change.
A user clicks a button, types in a field, checks a box, submits a form, or chooses an option.
React event handlers connect those actions to your JavaScript code.
The pattern is simple: user action → event handler → state update → screen update.
Handling clicks and input changes
import { useState } from "react";
function NamePreview() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
function handleClear() {
setName("");
}
return (
<section>
<label htmlFor="name">Name</label>
<input
id="name"
value={name}
onChange={handleChange}
/>
<p>Preview: {name}</p>
<button onClick={handleClear}>
Clear
</button>
</section>
);
}
onChange={handleChange} runs the function when the input value changes.
event.target.value reads what the user typed.
setName updates the component state.
value={name} keeps the input controlled by React state.
onClick={handleClear} runs code when the button is clicked.
Interaction
Events connect user actions to React code.
Forms
Inputs need events to capture what users type.
State changes
Events often update state, which updates the screen.
Clear flow
React interaction is easier when every event handler has one clear job.
Calling the function immediately by mistake
<button onClick={handleClear()}>
Clear
</button>
Passing the function as the handler
<button onClick={handleClear}>
Clear
</button>
Ask ChatGPT: "Which event handler runs for each user action in this React component?" Then trace click and typing actions yourself.
Create one input controlled by state.
Add an onChange handler.
Display the typed value below the input.
Add a clear button with onClick.
Explain the full flow from typing to screen update.
Calling a handler immediately instead of passing the function.
Forgetting to read event.target.value from an input event.
Mixing controlled and uncontrolled input behavior without understanding it.
Putting too many unrelated jobs in one event handler.
Forgetting that event names in React use camelCase.
Use React event handlers to respond to clicks and input changes, update state, and make the interface interactive.
Login - Jit4All
Login
Welcome back to Jit4All