Beginner React Interview QuestionsBeginnerPractical
React · Question 22
How do you create a controlled input in React?
Direct answer
Store the input value in state, pass that state to value, and synchronously update it from the input's onChange handler.
SearchBox.jsx
import { useState } from "react";
export default function SearchBox() {
const [query, setQuery] = useState("");
return (
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Search"
/>
);
}For a controlled text input, React state is the source of truth. Checkboxes and radio buttons are controlled with checked rather than their text value.