I followed the React Form tutorial to create the component below:
export default class SignInForm extends React.Component {
constructor(props) {
super(props)
this.state = {
email: '',
password: ''
}
this.onEmailChange = this.onEmailChange.bind(this)
this.onPasswordChange = this.onPasswordChange.bind(this)
}
onEmailChange(event) {
this.setState({email: event.target.value})
}
onPasswordChange(password) {
this.setState({password: event.target.value})
}
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<div>
<label>Email</label>
<div>
<input type="email"
placeholder="[email protected]"
onChange={this.onEmailChange}
value={this.state.email}
/>
</div>
</div>
<div>
<label>Password</label>
<div>
<input type="password"
placeholder="Password"
onChange={this.onPasswordChange}
value={this.state.password}
/>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
)
}
}
As soon as the form renders, I get the following error:
SignInForm is changing a controlled input of type password to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component
I cannot find the place where I am making it an uncontrolled component. What am I doing wrong?
The first way is by using the state within the component to handle the form data. This is called a controlled component. The second way is to let the DOM handle the form data by itself in the component. This is known as an uncontrolled component.
The official documentation defines controlled inputs as: The React component that renders an element also controls what happens in that element on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled input.”
The warning "A component is changing an uncontrolled input to be controlled" occurs when an input value is initialized to undefined but is later changed to a different value. To fix the warning, initialize the input value to an empty string, e.g. value={message || ''} . Here is an example of how the error occurs.
It looks like your onPasswordChange method should probably be:
onPasswordChange(event) {
this.setState({password: event.target.value})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With