Controlled Components
Explore the concept of controlled components in React forms. Learn how to synchronize form input values with React state, manage changes using event handlers, and handle different input types like text, checkboxes, radio buttons, and selects. Understand React's approach to keeping form data consistent and using state or external libraries for control.
We'll cover the following...
State changes
In order to portray state changes within form fields and transfer changes made by users in form fields into the state, a controlled component is needed. React fully takes care of the state handling of these form elements. We transfer a value to the value attribute which we receive from the state and also derive the changed value and pass it back to the state.
React state is seen as a single source of truth (or a similar state container like Redux). The only relevant value is the one that can be found in the React state, and the corresponding input in a form will constantly reflect this value in the state.
Let’s take a look at an example to illustrate this better:
import React from 'react';
import ReactDOM from 'react-dom';
import Controlled from './app.js';
require('./style.css');
ReactDOM.render(
<Controlled />,
document.getElementById('root')
);
At first glance, the controlled component does not look very different from the
uncontrolled component. The defining difference that turns this component into a
controlled one rather than uncontrolled lies in line 34 highlighted in the above code snippet. The value attribute of this <input/> ...