Controlled elements and Controlled Components both are same in React. In React, elements should follow a single source of truth.
In HTML, form elements such as
In HTML, form elements such as
<input>
, <textarea>
, and <select>
typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState()
.
We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
import React, { Component } from 'react';
class LoginForm extends Component {
username = React.createRef();
state = {
account:{username:'',password:''}
};
handleSubmit = e => {
// Call the server
e.preventDefault();
const username = this.username.current.value;
alert(username);
};
// componentDidMount()
// {
// this.username.current.focus();
// }
handleChange = e => {
const account = { ...this.state.account };
account.username = e.currentTarget.value;
this.setState({account});
}
render() {
return (
<div>
<div className="form-row">
<form onSubmit={this.handleSubmit}>
<div className="form-group col-md-12">
<label htmlFor="username">Email address</label>
<input autoFocus
value={this.state.account.username}
onChange={this.handleChange}
ref={this.username} type="email" className="form-control" id="username" aria-describedby="emailHelp" placeholder="Enter email" />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div className="form-group col-md-12">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" id="password" placeholder="Password" />
</div>
<div className="form-check">
<input type="checkbox" className="form-check-input" id="Check1" />
<label className="form-check-label" htmlFor="Check1">Check me out</label>
</div>
<button type="submit" className="btn btn-primary m-2">Submit</button>
</form>
</div>
</div>
);
}
}
export default LoginForm;
No comments:
Post a Comment