React - Uncontrolled Component (DOM State)

About

An uncontrolled component is a component such as form where the state is handled by the DOM itself (not react)

The inverse is called a controlled component where the state is controlled by React

Usage

if:

  • you need to write an very difficult event handler (for every way your data can change)
  • you are converting a preexisting codebase to React,
  • you are integrating a React application with a non-React library.

Example

with a input where a ref is used to get form values from the DOM.

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }

  handleSubmit(event) {
    console.log('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>
    );
  }
}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);
<div id="root"></div>

Documentation / Reference





Discover More
Examples of React Input Element with Class component

This page keeps the example with class component for a input The react forms components input accept a value attribute that is used to implement a controlled component. A React form: written as...
How to create a Select element in React?

This page is the creation of a HTML select element in React and how to handle it in a form In a non-controlled fashion, you need to read the value from the HTML select DOM element. form implementing...
React - Input Element

This page is the handling of input element in React. These examples are made with a function components. If you still want to see the same example with class component, they are here: The react...
What are React Forms?

A React form is the implementation of HTML form elements with HTML React elements It works a little bit differently from other DOM elements in React, because form elements naturally keep some internal...
What is a React Controlled Component?

A controlled component is a component such as a form element where its state is controlled by React. uncontrolled component In a controlled component, state is handled by the React component The nature...



Share this page:
Follow us:
Task Runner