Handling events & user input (forms)
Reacting to the user
A UI is alive when it responds to clicks, typing, and submitting. In React you handle these with event handlers — functions that run when something happens.
Handling a click
function App() {
function handleClick() {
alert("Button clicked!");
}
return <button onClick={handleClick}>Click me</button>;
}
Notice onClick={handleClick} — you pass the function itself, you do not call it (handleClick, not handleClick()). React calls it for you when the click happens.
Reading what the user types: controlled inputs
The React way to handle a form input is to connect it to state. This is called a controlled input:
function NameForm() {
const [name, setName] = useState("");
return (
<div>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Your name"
/>
<p>Hello, {name}!</p>
</div>
);
}
Here is the loop:
- The input shows
name(from state). - When the user types,
onChangeruns and callssetNamewith the new text (e.target.value). - State updates → component re-renders → the
<p>shows the new name live.
The state is the single source of truth, and the input always reflects it.
Handling form submit
function handleSubmit(e) {
e.preventDefault(); // stop the page from reloading
console.log("Submitted:", name);
}
<form onSubmit={handleSubmit}>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button type="submit">Send</button>
</form>
e.preventDefault() is important — without it, the browser reloads the page on submit and you lose everything.
Events: pass the function (
onClick={fn}). Forms: connect the input'svalueto state and update it inonChange. That two-way link is a "controlled input" — the React way.