Controlled Component
Displaying 1 - 1 of 1REACT: Controlled or Uncontrolled components
The form is one of the most-used HTML elements in web development.
Since the introduction of React, the way forms have been handled has changed in many ways.
In React, there are two ways to handle form data in our components:
The first way is the Controlled Component:
We handle form data by using the state within the component to handle the form data.
The Second way is Uncontrolled Component:
We let the DOM handle the form data by itself in the component.
Code Snippet
Controlled Component
import React, { Component } from 'react';
class App extends Component {
state = {
message: ''
}
updateMessage = (newText) => {
console.log(newText);
this.setState(() => ({
message: newText
}));
}
render() {
return (
<div className="App">
<div className="container">
<input type="text"
placeholder="Your message here.."
value={this.state.message}
onChange={(event) => this.updateMessage(event.target.value)}
/>
<p>the message is: {this.state.message}</p>
</div>
</div>
);
}
}