React Reference ยท Props and Attributes
React onChange prop
How onChange works in React: it fires on every keystroke, reading target.value and target.checked, controlled inputs, selects, files and common pitfalls.
In plain HTML, a text input fires change only when it loses focus. React's onChange behaves like the browser's input event instead: it fires on every edit, so you can keep state in step with what the user types. That is why onChange is the handler you pair with value on a controlled input.
The handler receives a change event. Read the new text from event.target.value, and the state of a checkbox from event.target.checked.
<input value={name} onChange={(e) => setName(e.target.value)} />
Try it
One handler can serve several fields when each input has a name.
Syntax
<input value={string} onChange={(event) => { ... }} /> <input type="checkbox" checked={boolean} onChange={(event) => { ... }} /> <select value={string} onChange={(event) => { ... }}>...</select> <textarea value={string} onChange={(event) => { ... }} />
| Name | Description |
|---|---|
event.target.value |
The new text of an input, textarea or select. Always a string, even for type="number". |
event.target.checked |
The new state of a checkbox or radio button. |
event.target.files |
A FileList for type="file". |
event.target.name |
The input's name, handy for shared handlers. |
event.currentTarget |
The element carrying the handler. |
Usage notes
- Controlled inputs need
onChange. GivingvaluewithoutonChange(and withoutreadOnly) makes the field read-only and logs a warning. - The handler runs after the DOM has changed, and React then restores the DOM to whatever your state says. If you do not update state, the typed character disappears.
- Numbers are strings. Convert with
Number(e.target.value); an empty string becomes0, so test for''first when that matters. <select multiple>: read selected options frome.target.selectedOptions.- File inputs are always uncontrolled; read
e.target.files[0]and never setvalue(other than to''). - Each keystroke re-renders. For expensive children, use
useDeferredValueor keep the field uncontrolled and read it on submit. onInputis also supported and fires at the same moments for text inputs. UseonChangefor consistency with the rest of React.- Custom components only have an
onChangeprop if you define one; it does not need to receive an event.