Controlled input

제어 입력

React state owns the input value and updates on every input event.

···
html
<div class="scene"><div class="title">KEYSTROKE LOOP</div><div class="field">search <span id="typed"></span><i></i></div><div class="path"><span id="event" class="pill">onChange</span><span>→</span><span id="state" class="pill">state</span><span>→</span><span id="value" class="pill">value</span></div><div class="caption" id="caption">type → update → paint</div></div>
css
.scene{width:min(94vw,800px);height:min(86vh,320px);position:relative;overflow:hidden;display:flex;flex-direction:column;justify-content:space-between;border:1px solid var(--line);border-radius:14px;background:var(--surface);padding:clamp(9px,2.4vmin,20px);font:500 clamp(15px,4vmin,18px)/1.3 var(--font-sans,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}.scene b,.scene strong{font-weight:700}.label{color:var(--muted)}.code{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.pill{border:1px solid var(--line);border-radius:8px;padding:.4em .65em;background:var(--bg)}.active{border-color:var(--accent)!important;color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 10%,var(--surface))!important}.title{font-weight:700;color:var(--accent)}.field{margin:clamp(10px,5vmin,38px) auto 10px;width:82%;padding:.7em;border:1px solid var(--accent);border-radius:9px;font-family:ui-monospace,monospace}.field i{display:inline-block;width:2px;height:1em;background:var(--accent);animation:blink .7s steps(1) infinite;vertical-align:-.15em}@keyframes blink{50%{opacity:0}}.path{display:flex;align-items:center;justify-content:space-around;gap:4px}.path .pill{min-width:22%;text-align:center}.caption{text-align:center;color:var(--muted);margin-top:10px}
js
const words=["","r","re","rea","react"];let n=0;function tick(){const word=words[n%words.length];document.getElementById("typed").textContent=word;["event","state","value"].forEach((id,i)=>document.getElementById(id).classList.toggle("active",i===n%3));document.getElementById("caption").textContent="state: "+word;n++}tick();setInterval(tick,650)

A controlled input reads its value from state and updates that state in onChange. Validation and displayed text can derive from the same source.

The demo follows a keystroke from event to state and back to the screen. Since every keystroke updates state, move it into a smaller component if a large subtree also renders.

When to use

Use it for live validation, conditional UI, or coordination between fields.

Open as page ↗