0 votes
in ReactJS by
What are the differences between controlled and uncontrolled components?

1 Answer

0 votes
by

Controlled and uncontrolled components are just different approaches to handling input form elements in react.

Feature Uncontrolled Controlled Name attrs

One-time value retrieval (e.g. on submit) ✔️ ✔️ ✔️

Validating on submit ✔️ ✔️ ✔️

Field-level Validation ✔️ ✔️

Conditionally disabling submit button ✔️ ✔️

Enforcing input format ✔️ ✔️

several inputs for one piece of data ✔️ ✔️

dynamic inputs ✔️ 🤔

Controlled component In a controlled component, the value of the input element is controlled by React.

We store the state of the input element inside the code, and by using event-based callbacks, any changes made to the input element will be reflected in the code as well.

When a user enters data inside the input element of a controlled component, onChange function gets triggered and inside the code we check whether the value entered is valid or invalid. If the value is valid, we change the state and re-render the input element with new value.

Example of a controlled component:

function FormValidation(props) {

 let [inputValue, setInputValue] = useState("");

 let updateInput = e => {

   setInputValue(e.target.value);

 };

 return (

   <div>

     <form>

       <input type="text" value={inputValue} onChange={updateInput} />

     </form>

   </div>

 );

}

As one can see in the code above, the value of the input element is determined by the state of the inputValue variable. Any changes made to the input element is handled by the updateInput function.

Uncontrolled component In an uncontrolled component, the value of the input element is handled by the DOM itself.

Input elements inside uncontrolled components work just like normal HTML input form elements.

The state of the input element is handled by the DOM. Whenever the value of the input element is changed,event-based callbacks are not called. Basically, react does not perform any action when there are changes made to the input element.

Whenever use enters data inside the input field, the updated data is shown directly. To access the value of the input element, we can use ref.

Example of an uncontrolled component:

function FormValidation(props) {

 let inputValue = React.createRef();

 let handleSubmit = e => {

   alert(`Input value: ${inputValue.current.value}`);

   e.preventDefault();

 };

 return (

   <div>

     <form onSubmit={handleSubmit}>

       <input type="text" ref={inputValue} />

       <button type="submit">Submit</button>

     </form>

   </div>

 );

}

As one can see in the code above, we are not using onChange function to govern the changes made to the input element. Instead, we are using ref to access the value of the input element.

...