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>