Reactbeginner 8 min
Respond to clicks and typing, and build a controlled text input.
How to attach event handlers, and how to keep an input's text in state (a controlled input).
Interfaces are conversations: the user acts, the screen answers. Handling events and inputs is the heart of every interactive React app.
React events look like HTML attributes but in camelCase: onClick, onChange, onSubmit. You pass a function, not a string and not a call.
For text boxes, the common pattern is a controlled input: the input's value always comes from state, and every change updates state.
e.target.value is what the user just typed. Because the value comes from state, React is always in charge of what is displayed.
name holds the text and greeted remembers whether the button was pressed.onChange. We store the new text and reset greeted.disabled while the name is empty.greeted to true, and the paragraph switches to the greeting.Add a second input for a last name and show the full name in the greeting.
onClick={save()} runs it during render. Write onClick={save} or onClick={() => save()}.value without onChange, which makes the input read-only.onclick. React uses onClick.e.target.value and storing the whole event.onChange.fn or () => fn(), never fn().You finished the React beginner section. Next: lists, effects, forms and routing.
<button onClick={handleClick}>Save</button><input value={text} onChange={(e) => setText(e.target.value)} />function App() {
const [name, setName] = useState("");
const [greeted, setGreeted] = useState(false);
return (
<div style={{ fontFamily: "system-ui" }}>
<input
value={name}
onChange={(e) => {
setName(e.target.value);
setGreeted(false);
}}
placeholder="Your name"
/>
<button onClick={() => setGreeted(true)} disabled={name === ""}>
Greet
</button>
<p>{greeted ? "Hello, " + name + "!" : "Type your name, then press Greet."}</p>
</div>
);
}