Controlled and Uncontrolled Components in React

In this part, we will learn about react forms, controlled and uncontrolled components. React forms are little different from actual HTML forms because form elements keep the initial state. There are two types : Controlled Component and Uncontrolled Component.

Basically, we use the React forms to extract the user input or data in our React application, So we can use this data in the back end or somewhere else. This is why forms are pretty important to understand.

First let’s see and which is actually familiar to beginner is simple and plain form in react:

function ContactForm() {
  return (
    <form>
      <div>
        <label htmlFor="name">Name</label>
        <input id="name" type="text" />
      </div>
      <div>
        <label htmlFor="email">Email</label>
        <input id="email" type="email" />
      </div>
      <div>
        <label htmlFor="message">Message</label>
        <textarea id="message" />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

In this example, we have created a simple contact form, and you’re pretty familiar with this. And we didn’t have used states and any library to create this form, so this very simple form we have created.

There are basically two types of form components: Controlled and Uncontrolled components

Controlled Components React

Generally, form elements like <textarea>, <submit>, <select> etc. maintains their own state and updates the states by itself as per user input. But we want that form element and form values should be controlled by React is known as controlled component.

Generally, if we talk about HTML form behavior, The forms in HTML redirects to the new page when submitting the form. So if we need this thing in our React, then we can use controlled components.

In controlled component, we need to use states to hold the values, and update it when the value gets changed.

For example,

import React from 'react'
import { useState } from 'react';

const App =() =>{
    const [value,setValue] = useState("");
    const [name, setName] = useState();
   
    const Submitted = (event)=>{
        event.preventDefault();
        setName(value);
    }

    const update =(event) =>{
        
        setValue(event.target.value);
    }

    return(
        <form onSubmit={Submitted}>

            <div>
                <h1>Hello {name}</h1>
                <input type='text' placeholder='enter your name' value={value}
                onChange={update}></input>
                <button type='submit'>click me</button>
            </div>
        </form>
   )
}
export default App;

In the above Example, we made a simple form which have some states to hold some values given by user. So here, we made a pretty simple form where we have an input field, heading and button. You can say we have created form as we do in HTML. So of course, elements are pretty the same as HTML elements.

Now for this example, it is the best example to tell you why and when we should use controlled component for forms. In here we are taking input from user let’s say name and if the submit button pressed then the name will be reflected on heading.

Output

Controlled and Uncontrolled Components

Uncontrolled Component React

Uncontrolled components are sometimes required to use in some application, where we don’t need to add and hold the current values in the state. Simply, this type of forms are not in control of React because here we don’t use any useState hook or Event handler to hold the value. Instead of that, we use ref element to get values directly from DOM.

It is slightly easy to implement than controlled component, also it requires less code than controlled component. For example, if we create a simple form as we do in HTML, so that will be an uncontrolled form, that code would be easy. right?

Again, you can convert that form into the controlled form, but you need some more code which might be boring to you but believe uncontrolled components and forms should be used for very specific situations.

Let’s see an Example for uncontrolled component form:

import React from 'react'

class NameForm extends React.Component {
    constructor(props) {
      super(props);
      this.handleSubmit = this.handleSubmit.bind(this);
      this.input = React.createRef();
    }
  
    handleSubmit(event) {
      alert('A name was submitted: ' + this.input.current.value);
      event.preventDefault();
    }
  
    render() {
      return (
        <form onSubmit={this.handleSubmit}>
          <label>
            Name:
            <input type="text" ref={this.input} />
          </label>
          <input type="submit" value="Submit" />
        </form>
      );
    }
  }

export default NameForm;

We have here created a simple form which take an input, and we are just putting alert message with the user added name. As we can see here, user’s input value is not stored anywhere like we are not storing it. Simply, it is not under control of React because there are no states to hold the information here. We are just getting the name and alerting the user with its name.

So this kind of forms are known as uncontrolled forms and we this component is not under control of React, so this is uncontrolled component.

When and Why to Use Controlled Inputs

In react, Controlled component or Controlled Inputs are pretty useful, and it is recommended by react itself to use controlled components, so that updating and modifications in form could be easier. In case of uncontrolled component, update and modification can be complicated. Also, with the help of controlled component elements of form can be controlled with react.

There are some use cases where controlled component and inputs:

  • Instantly validating the form on every key press: useful if you want to keep the Submit button disabled until everything is valid, for instance.
  • Handling formatted input, like a credit card number field, or preventing certain characters from being typed.
  • Keeping multiple inputs in sync with each other when they’re based on the same data.

Difference Between Controlled and Uncontrolled Components in react

Now let’s see some basic differences between Controlled Components and Uncontrolled Components

Controlled  ComponentsUncontrolled Components
These components are under control in component state and react.These components are under the control of DOM.
Controlled components are predictable since they are controlled by state.Uncontrolled components are unpredictable because there is a chance of data loss during its life-cycle.
In these components, internal state is not maintainedIn these components, Internal state is maintained
It takes the current value as propsit takes the values using refs
It allows validation control.It does not allow validation control.
Have better control on the form data and valuesHas very limited control over form values and data

Check out video reference here:

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents