Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Controlled and Uncontrolled Components in React

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

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 which is familiar to beginners 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. We didn’t use states and any library to create this form, so this very simple form we have created.

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

Controlled Components React

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

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

In the 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 that has some states to hold some values given by the 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 much the same as HTML elements.

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

Output

Controlled and Uncontrolled Components

Uncontrolled Component React

Uncontrolled components are sometimes required to be used in some applications, where we don’t need to add and hold the current values in the state. Simply, this type of form is 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 easier to implement than a controlled component, also it requires less code than a controlled component. For example, if we create a simple form as we do in HTML, that will be an uncontrolled form, and 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 of an 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 that takes input, and we are just putting an alert message with the user’s added name. As we can see here, the user’s input value is not stored anywhere like we are not storing it. Simply, it is not under the 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.

This kind of form is known as the uncontrolled form and this component is not under the control of React, so this is an uncontrolled component.

When and Why to Use Controlled Inputs

In React, Controlled components 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 the case of uncontrolled components, updates, and modifications can be complicated. Also, with the help of controlled components elements of form can be controlled with react.

There are some use cases where controlled components 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 the state.Uncontrolled components are unpredictable because there is a chance of data loss during their life cycle.
In these components, the internal state is not maintainedIn these components, the 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 over the form data and valuesHas very limited control over form values and data

Check out the 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.

One comment

Leave a Reply

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

Table of Contents