Sub topic 12
Controlled inputs for the search box and checkbox
This chapter assumes you have read the earlier chapters on props, state, and inverse data flow. You should know that FilterableProductTable owns filterText and inStockOnly, and that it passes setter functions down to SearchBar as callback props. Here we look at what makes the two form fields in SearchBar work: they are controlled inputs.
What "controlled" means
A browser input normally keeps its own value. You type, the DOM updates, and you read the value later. React calls that an uncontrolled input, because the DOM is the source of truth.
A controlled input reverses that arrangement. React state is the source of truth, and the input only displays what it is given. The component does three things:
- It passes the current state to the input through
value(text) orchecked(checkbox). - It listens to
onChange. - In the handler, it asks the owner of the state to store the new value.
Here is the SearchBar from the running example:
function SearchBar({
filterText,
inStockOnly,
onFilterTextChange,
onInStockOnlyChange
}) {
return (
<form>
<input
type="text"
value={filterText}
placeholder="Search..."
onChange={(e) => onFilterTextChange(e.target.value)}
/>
<label>
<input
type="checkbox"
checked={inStockOnly}
onChange={(e) => onInStockOnlyChange(e.target.checked)}
/>{' '}
Only show products in stock
</label>
</form>
);
}SearchBar has no state of its own. It receives filterText and inStockOnly as props, and it receives two callbacks that report changes. Every character the user types takes a round trip through the parent before it appears in the box.
The round trip for one keystroke
Suppose the user types "a" into an empty search box. The DOM does not simply keep the "a". React runs your handler, you request a state update, React re-renders, and the input is given the new value.
This is the inverse data flow from the previous chapter, seen through a single input. Data still moves one way at a time. Changes go up through a callback, and new values come down through props.
The parent that owns the state
Here is the parent again, with the setters passed straight through as callbacks:
import { useState } from 'react';
function FilterableProductTable({ products }) {
const [filterText, setFilterText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
return (
<div>
<SearchBar
filterText={filterText}
inStockOnly={inStockOnly}
onFilterTextChange={setFilterText}
onInStockOnlyChange={setInStockOnly}
/>
<ProductTable
products={products}
filterText={filterText}
inStockOnly={inStockOnly}
/>
</div>
);
}Passing setFilterText directly works because a state setter accepts a new value. SearchBar calls onFilterTextChange(e.target.value), which is the same as setFilterText(e.target.value). If you want to normalize input first, for example trimming whitespace, wrap the setter in your own function and pass that function instead. Only the owner of the state needs to change.
Text inputs use `value`, checkboxes use `checked`
The two fields look alike but read from different properties.
| Input type | Prop that sets what is shown | Where the new value is read in the event |
|---|---|---|
| Text | `value` | `e.target.value` |
| Checkbox | `checked` | `e.target.checked` |
| Radio | `checked` | `e.target.checked` (compare `e.target.value` to choose the option) |
For a checkbox, e.target.value is the static string attribute of the element, which is "on" by default. It does not tell you whether the box is ticked. Reading it instead of checked is a common bug, and it produces a filter that never turns off.
Why the filter updates instantly
ProductTable receives filterText and inStockOnly as props. It filters the product list during render, as shown earlier in this tutorial. The text box and the visible rows are therefore always consistent. They are two views of the same two state values, and they cannot drift apart.
If you had kept a copy of the text inside SearchBar (for example useState('') there) and also sent the text up, you would have two sources of truth. Sooner or later they would disagree, for instance after a "Clear filters" button that resets only the parent's copy. A controlled input avoids this because the input never has a value that React state does not know about.
Common errors
Setting `value` without `onChange`
<input type="text" value={filterText} />React warns that you provided a value prop without an onChange handler. The field becomes read-only: you type, React re-renders with the unchanged filterText, and the character vanishes. If you really want a read-only field, add the readOnly attribute. Otherwise add onChange.
Calling the callback during render
<input
type="text"
value={filterText}
onChange={onFilterTextChange(e.target.value)} // wrong
/>This is wrong for two reasons. e does not exist at that point, so it throws. And even without the error, the call would run while rendering instead of when the event happens. onChange needs a function, so wrap the call in an arrow function: onChange={(e) => onFilterTextChange(e.target.value)}.
Switching from uncontrolled to controlled
const [filterText, setFilterText] = useState(); // undefined at firstIf value is undefined on the first render, React treats the input as uncontrolled. When state later becomes a string, React warns that the input changed from uncontrolled to controlled. Give state a real initial value, '' for text and false for a checkbox. Likewise, never pass null as a value, because it can cause the same warning. If the data can be missing, convert it with value={filterText ?? ''}.
Reading state right after setting it
onChange={(e) => {
setFilterText(e.target.value);
console.log(filterText); // still the old value
}}State in a render is a snapshot. filterText keeps its old value for the rest of that handler, and the new value arrives on the next render. If you need the new value in the handler, use the local variable you already have, e.target.value.
Storing derived data
A tempting fix for "the table does not update" is to add a visibleProducts state and sync it in the change handler. This duplicates information that can already be computed from products, filterText, and inStockOnly. Keep the filtering inside ProductTable and let the two state values drive it.
Behavior worth knowing
- Re-render cost. Every keystroke re-renders
FilterableProductTableand its children. For a small table this is not noticeable. For a very large list, you can reduce the work with techniques such asuseDeferredValueor memoization. Measure first, because the controlled pattern itself is rarely the bottleneck. - Cursor position. If your handler changes the text before storing it, for example forcing uppercase, React may move the cursor to the end of the field. Transforming the value on display is often safer than transforming it on input.
- The form element. Pressing Enter inside a text field in a
<form>submits it, and the browser reloads the page. This search bar needs no submit, so either leave the form without a submit button, which still allows Enter-to-submit on a single text field, or addonSubmit={(e) => e.preventDefault()}. - Accessibility. The checkbox is already wrapped in a
<label>, so clicking the text toggles it. The text input has only a placeholder, which is not a reliable label for screen readers. Addingaria-label="Search products"to the input fixes that without changing the layout.
A small stand-alone check
You can see the whole loop in a single file, without the table:
import { useState } from 'react';
export default function CheckboxDemo() {
const [text, setText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
return (
<form onSubmit={(e) => e.preventDefault()}>
<input
type="text"
aria-label="Search products"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<label>
<input
type="checkbox"
checked={inStockOnly}
onChange={(e) => setInStockOnly(e.target.checked)}
/>{' '}
Only show products in stock
</label>
<p>
Text: "{text}" | In stock only: {String(inStockOnly)}
</p>
</form>
);
}Type and tick the box. The paragraph always matches what you see, because both come from the same two state values. Now delete the onChange from the text input and type again. The field stops accepting characters, which shows what the controlled pattern requires of you.
Exercise
A teammate writes <input type="checkbox" checked={inStockOnly} onChange={(e) => onInStockOnlyChange(e.target.value)} />. The box ticks, but the "in stock only" filter behaves strangely: it never turns off once on. What is wrong, and what is the fix?
Show answer
For a checkbox, e.target.value is the element's static value attribute, which defaults to the string "on", not the checked state. Every change therefore sets inStockOnly to the truthy string "on". Read e.target.checked instead, which is a boolean: onChange={(e) => onInStockOnlyChange(e.target.checked)}.
Exercise
You add a "Clear" button in FilterableProductTable that calls setFilterText(''). After clicking it, should SearchBar need any change for the text box to empty, and why?
Show answer
No. The text box is controlled by the filterText prop. When the parent sets the state to an empty string, it re-renders and passes filterText="" down, so the input displays an empty value. This is why a single source of truth makes resets simple.