React UnControlled Component Example


Uncontrolled component is a component in which the value of the input field is managed by the browser. The component does not manage the state of the input, and instead relies on the browser to update the input field value when the user interacts with it. Uncontrolled components use the defaultValue attribute of the input element to set the initial value of the input.

Uncontrolled components are useful when you have a simple form that does not require complex validation or manipulation of the input value.

Here’s an example of an Uncontrolled Component in React:

import React, { Component } from 'react';

class UncontrolledComponent extends Component {
  handleSubmit = (event) => {
    event.preventDefault();
    console.log('Submitted value: ', this.input.value);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Enter a value:
          <input
            type="text"
            ref={(input) => this.input = input}
          />
        </label>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

export default UncontrolledComponent;

In this example, we have an UncontrolledComponent that uses an uncontrolled input field. The input field is uncontrolled because its value is not managed by React state, but instead accessed directly using a ref.

The UncontrolledComponent renders a form with an input field and a submit button. The input field is an uncontrolled component because it does not receive its value from the state of the UncontrolledComponent.

The handleSubmit method is called when the user submits the form. It accesses the value of the input field using the ref and logs it to the console.

Overall, the UncontrolledComponent does not manage the state of the input field, and relies on accessing the value of the input field directly. This makes it harder to perform validation on the input before submission, but can be useful in certain situations where it is not necessary to manage the state of the input field.