How to get the value of an input element in React
By Flavio Copes
Learn how to get the value of a form input in React by storing it in state with useState and updating it from the input onChange event handler.
To get the value of an input element in React, store it in a state variable with the useState hook, and update it in the input’s onChange event handler. The current value is then always available in your component, ready to use when the user submits the form.
This pattern is called a controlled component. React state is the single source of truth for what the input contains.
Storing the value in state
A common scenario involves having a form, and you want to get the value of one of the form fields, for example when the user clicks a button.
First, create a state variable for the field:
const [title, setTitle] = useState('')
Then wire the input to it in JSX:
<input value={title} onChange={event => setTitle(event.target.value)} />
event.target is the input DOM element. event.target.value is the text it currently contains.
Every keystroke fires onChange, which calls setTitle(). The component re-renders, and title always holds what the user typed.
Reading the value on submit
Here’s a complete example, a small form to add a book:
import { useState } from 'react'
function AddBook() {
const [title, setTitle] = useState('')
const handleSubmit = event => {
event.preventDefault()
console.log(title) //'The Pragmatic Programmer'
}
return (
<form onSubmit={handleSubmit}>
<input value={title} onChange={event => setTitle(event.target.value)} />
<button>Add book</button>
</form>
)
}
export default AddBook
In handleSubmit you don’t touch the DOM at all. The value is already in title.
Notice I initialized the state with an empty string. If you call useState() with no argument, title starts as undefined. React then logs a warning about the input switching from uncontrolled to controlled. Starting from '' avoids that.
What about checkboxes?
Text inputs, textareas and selects all use event.target.value. Checkboxes are different: read event.target.checked instead, which is a boolean:
<input
type='checkbox'
checked={published}
onChange={event => setPublished(event.target.checked)}
/>
A common pitfall
State updates are not immediate. If you call setTitle() and read title on the next line, you still get the old value. The new value is only available on the next render.
If you need the fresh value right inside the handler, read it from event.target.value directly instead of from state.
Related posts about react: