Open In App

React.js | Uncontrolled Vs Controlled Inputs

Improve
Improve
Like Article
Like
Save
Share
Report

In HTML, form elements such as <input>, <textarea>, <select>, etc typically maintain their own state and update it based on user input. In React, a mutable (changeable) state is usually kept in the state property of components. 
In React forms input value can be of two types according to your choice: uncontrolled and controlled values.
Uncontrolled input: With uncontrolled input values, there is no updating or changing of any states. It maintains its own internal state, which basically means it remembers what you typed in the field. That value can be exploited by pulling it using the ref keyword whenever it needs to be used. In uncontrolled inputs, the value you submit is the value you get.
 

Now, Open your react project and edit the index.js file in the src folder:

src index.js:

Javascript




import React from 'react';
import ReactDOM from 'react-dom';
import NameForm from './NameForm';
 
ReactDOM.render(
  <React.StrictMode>
    <NameForm />
  </React.StrictMode>,
  document.getElementById('root')
);


Create a Component name NameForm.js in react project:

Now, Open your react project and edit the NameForm.js file in the src folder:

src NameForm.js:
 

javascript




import React,{Component} from 'react';
 
class NameForm extends  React.Component {
    handleClick = () => {
      const name = this._name.value;
      alert('Hello ', name);
    }
   
    render() {
      return (
        <div>
          <input type="text" ref=
                {inputValue => this._name = inputValue}
             
            placeholder="Enter your name" />
            <button onClick={this.handleClick}>
                Done
            </button>
        </div>
     );
    }
  }
 
export default NameForm;


Input: Tanisha 
Output: Hello Tanisha (Display on the alert box) 
 

Controlled input: In controlled inputs, there is at all times some sort of changes and amendments going on in the field, every single character entered and even something like a backspace would count as a change. The current value of the input field will be a prop of the class component (usually it will live in the state referred to by using this.state.varName.) as they don’t maintain their internal state. There will also be a callback function (like onChange, onClick, etc) that is necessary to handle the changes (in value) occurring in the input field, which makes them controllable. 
Now, Open your react project and edit the NameForm.js file in the src folder:
src NameForm.js:

javascript




import React,{Component} from 'react';
 
 
class NameForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: '',
        };
    }
    
    handleNameChange = (event) => {
        this.setState({ name: event.target.value });
    };
    
    render() {
        return (
            <div>
                <input type="text" onChange=
                        {this.handleNameChange}
                        placeholder="Enter your name" />
                <h1>{this.state.name}</h1>
            </div>
        );
    }
}
 
export default NameForm;


Input: Tanisha 
Output: Tanisha (Displaying on the screen letter by letter as the user types) 
 

Which one is better? 
It’s evident that controlled and uncontrolled form fields each have their individual benefits. You might need to use both or either depending on what the situation calls for. If you are making a simple form with little to no UI feedback and no need for instant validation (which means you only would validate and/or need the values when you submit), using uncontrolled inputs with refs is what you should go for. It would keep the source of truth in the DOM making it quicker and requiring lesser code. If you need more UI feedback and take into account every little change in the particular input field go for controlled input.
 



Last Updated : 29 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads