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
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 - 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...
React - Form

HTML form elements work a little bit differently from other DOM elements in React, because form elements naturally keep some internal state. : The state is controlled by React : The state is controlled...
React - Input Element

This page is the handling of input element in React. The react forms components input accept a value attribute that is used to implement a controlled component. A React form: written as a class...
What is a React Ref?

A ref is a state object that holds a value in its current property for the entire lifetime of the component. It's used to hold information that isn’t used for rendering. Unlike with state, updating...



Share this page:
Follow us:
Task Runner