top of page
Logo der Online Agentur mdwp

Uncontrolled component

In React JS, an Uncontrolled Component is a component that maintains its own internal state.

Most inputs in a form, such as a text field, a checkbox, or a radio button, maintain their own state which they update based on user input. In a conventional React setup, we can make these form inputs controlled by managing the value of these inputs through the component’s state and updating it via the setState method.

An Uncontrolled Component, however, doesn't link the input to the state. Instead, it uses the default HTML form behaviors and retrieves the current values directly from the DOM when necessary. In essence, with Uncontrolled Components, you allow the form data to be handled by the DOM itself rather than by the React component state.

Here is a code snippet that demonstrates an Uncontrolled Component:

```javascript
class Form 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>
);
}
}
```

In this code, the input element is a typical HTML form input and is not controlled by any state. The value of the input is retrieved directly when needed using “this.input.current.value” which points to the actual value of the input field in the DOM.

bottom of page