React - Uncontrolled Component (DOM State)

React Mapping Html Javascript

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





Recommended Pages
React Mapping Html Javascript
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 Mapping Html Javascript
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...
React Mapping Html Javascript
React - 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 component where the state is controlled...
React Mapping Html Javascript
React - Ref

A ref is a reference to: a DOM element or a React element Parent components can get the element by reference and manipulate them Managing focus, text selection, or media playback. Triggering...



Share this page:
Follow us:
Task Runner