How to Get the Value of an Input Field in React
- How Inputs Work in React
- Get the Value of Input Field in React 16
- Get the Value of the Input Field in React Using Hooks
- How to Handle Large Forms with Dozens of Inputs
Handling user inputs is one of the keys to developing dynamic React applications. Working with user inputs allows you to respond to their actions and provide a superior user experience.
When working in React, it’s good to store user inputs in the state properties to establish a single source of truth. This lets you easily interact with the data and manipulate it when necessary.
Whenever the state changes, React automatically updates the component to reflect the most recent changes.
How Inputs Work in React
Before proceeding any further, we must understand when and why React decides to re-render a component.
First, the application UI is updated (re-rendered) when its internal state changes. Any user event, such as selecting a different option or checking/unchecking a field, can change the state and cause a re-render.
Second, the re-render happens when a change in component props, which is received from the parent. In some cases, the parent component provides prop
values from its state.
React uses JSX, which looks a lot like HTML, but it functions differently.
It is important to keep in mind that when you create an <input>
element in JSX, you’re not creating the HTML <input>
element, but a React input
object that closely resembles it. It renders similar to the HTML input
element and imitates its event handling interface, but it is otherwise independent.
React applications are made up of UI elements, which get their values from the component state. As mentioned before, changing input is one of the most common ways to change the state, and by extension, the visual elements rendered on the page.
However, the important thing to keep in mind is that the state is the single source of truth in React applications. The UI interface has a secondary role.
Get the Value of Input Field in React 16
Since the release of React 16, developers can create React class components using readable class syntax. Please note that you must either bind them in the constructor function or call them using the arrow syntax for event handlers to work, like in the example below.
class App extends Component {
constructor(props){
super(props)
this.state = {
enteredValue: ""
}
}
render() {
console.log(this.state.enteredValue)
return <input type="text"
onChange={(event) => this.setState({enteredValue: event.target.value})}>
</input>;
}
}
In general, it’s more readable and convenient to use arrow syntax. It also makes applications easier to debug.
You can check out the playcode yourself and see that whenever you (aka the user) enter something new in the input field, the state value is updated and then logged to the console (for demonstration purposes).
Get the Value of the Input Field in React Using Hooks
Functional components are even easier to write and read than class components. This type of component is just a function that accepts props
as an argument.
Until a few years ago, functional components were also called stateless or dumb components and were mostly used to visualize the data.
Since React 16.8, functional components have gained access to many new features, including hooks. Now the developers can use the useState()
hook to maintain a state in a functional component.
This hook allows you to get one state variable and the function to update it. You don’t have to use the .setState()
API directly in functional components anymore.
Here’s what the same application would look like if it was built with functional components:
function App(props){
let [inputValue, setInputValue] = useState("")
console.log(inputValue)
return <input type="text"
onChange={(event) => setInputValue(event.target.value)}>
</input>;
}
useState()
hook works in a very simple way. Once called, it returns a state variable assigned to the inputValue
and a function to update it.
Having a distinct function for updating each variable can be beneficial from a readability perspective. As we can see, setInputValue
has a fairly descriptive name.
The argument passed to the useState()
hook (empty string) will be used as an initial value for the inputValue
state variable.
As you can see, this definition is much cleaner and works just as well as a class component. Functional components are usually the better choice whenever you need a component with just a few variables to store state value.
Still, in some cases, Class Components are necessary and different from functional components. To learn more about the differences, read the official react documentation.
How to Handle Large Forms with Dozens of Inputs
As we mentioned before, you need a state variable for every UI input element to hold the value entered by users. It is not unusual for forms to have dozens of inputs, even hundreds. Should you create a separate state variable for them all?
The solution is simple and in line with the overall logic of React. Instead of having these inputs in one large component, you should break them up into logically connected pieces by creating separate small components.
Then you can import and use them to build out your large form. This way, smaller components are only responsible for storing and maintaining a few inputs.
Apps structured this way are more readable and easier to maintain. Other developers working on your code will thank you for writing simple and understandable code.
Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.
LinkedIn