AI Hints
React · Lesson 25 of 120

Forms

Controlled inputs.

⏱ 2 min read▶ Video at 19:36🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

In React, form inputs are usually controlled. The input's value comes from state, and every keystroke updates that state. So React always knows exactly what's typed.

  • Value from state
  • Keystrokes update it
  • React always knows

A controlled input

Name state starts empty. The input's value is name, and on change sets it to what was typed. The greeting below updates on every key. We type a name. Run it.

App.jsxjsx
import { useState } from "react";

export default function App() {
  const [name, setName] = useState("");

  return (
    <div>
      <input id="name" value={name} onChange={e => setName(e.target.value)} placeholder="Your name" />
      <p>Hello, {name || "stranger"}!</p>
    </div>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"type": "#name", "text": "Priya"}]

Value and onChange

Value makes the input show the state. On change updates the state as the user types. You need both. With only value, the input is stuck. E dot target dot value is the text typed so far.

keyvalue
valueshows the state
onChangeupdates the state
Bothalways together
e.target.valuethe typed text

Summary

Controlled inputs take their value from state, and update it on change. Next, several inputs.

Key takeaways
  • value={name}
  • onChange
  • Always in sync
Next up: Several Inputs — one state object