Controlled Component in React Js
In every web application, handing form data is very basic requirement and if you want to handle this requirement in react Js, it provides two ways controlled component and uncontrolled component.
According to official document of React Js, it is recommended that in most of cases, controlled component should be implemented for Forms, but in this post, we will discuss about controlled component.
In controlled component, Form data is stored in component's state and updated by "onChangeHandler"
We can use single event handler for handling all form fields, regardless of type.
|
Controlled Component in react js |
Sample Code:
A) Class Component
a) App.js
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.onChangeHandler = this.onChangeHandler.bind(this);
this.state = { firstName: '', lastName: '', fullName: '' };
}
onChangeHandler(e) {
e.preventDefault();
this.setState({
[e.target.name]: e.target.value,
});
}
handleSubmit(e) {
this.setState({
fullName: this.state.firstName + ' ' + this.state.lastName,
});
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>Handling Form Data - Controlled Component</label> <br />
<br />
<label>
First Name:
<input
value={this.state.firstName}
type="text"
name="firstName"
onChange={this.onChangeHandler}
/>
</label>{' '}
<br />
<label>
Last Name:
<input
value={this.state.lastName}
type="text"
name="lastName"
onChange={this.onChangeHandler}
/>
</label>
<br />
<br />
<input type="submit" value="Submit" /> <br /> <br />
<label>Full Name :{this.state.fullName}</label>
</form>
);
}
}
export default App;
B) Functional Component
a) App.js
import React, { useState } from 'react';
export default function App() {
const [state, setState] = useState({
firstName: '',
lastName: '',
fullName: '',
});
function onChangeHandler(e) {
e.preventDefault();
setState({ ...state, [e.target.name]: e.target.value });
}
function handleSubmit(e) {
setState({ ...state, fullName: state.firstName + ' ' + state.lastName });
e.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<label>Handling Form Data - Controlled Component</label> <br />
<br />
<label>
First Name:
<input
value={state.firstName}
type="text"
name="firstName"
onChange={onChangeHandler}
/>
</label>{' '}
<br />
<label>
Last Name:
<input
value={state.lastName}
type="text"
name="lastName"
onChange={onChangeHandler}
/>
</label>
<br />
<br />
<input type="submit" value="Submit" /> <br /> <br />
<label>Full Name :{state.fullName}</label>
</form>
);
}
Happy Learning!! Happy Coding!!
Comments