-
Notifications
You must be signed in to change notification settings - Fork 50.5k
Description
Do you want to request a feature or report a bug?
Bug
What is the current behavior?
In v. 16.3.1, when I use the getDerivedStateFromProps method and I have a controlled component where the value of input field is this.state.{thefieldname}, I get a warning/error that says I am switching from controlled to uncontrolled or vice versa. If I remove the getDerivedStateFromProps, the error goes away.
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:
class UserSettings extends Component {
constructor(props) {
super(props)
this.state = {
firstName: '',
lastName: '',
email: ''
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
})
}
handleUpdateUser(e) {
e.preventDefault()
const { updateUser, uid } = this.props
updateUser(uid, this.state)
}
static getDerivedStateFromProps(nextProps) {
return {
firstName: nextProps.user.firstName,
lastName: nextProps.user.lastName,
email: nextProps.user.email
}
}
render() {
const { firstName, lastName, email } = this.state
return (
<section>
<h2>Settings</h2>
<form className="form-horizontal col-lg-6">
<p>{this.props.user.authStatus}</p>
<div className="form-group">
<label className="col-lg-2 control-label">First Name</label>
<div className="col-lg-10">
<input
type="text"
className="form-control"
name="firstName"
placeholder="First name"
value={firstName}
onChange={this.handleChange}
/>
</div>
<label className="col-lg-2 control-label">Last Name</label>
<div className="col-lg-10">
<input
type="text"
className="form-control"
name="lastName"
placeholder="Last name"
value={lastName}
onChange={this.handleChange}
/>
</div>
<label className="col-lg-2 control-label">Email</label>
<div className="col-lg-10">
<input
type="text"
className="form-control"
name="email"
placeholder="Email"
value={email}
onChange={this.handleChange}
/>
</div>
</div>
<div className="form-group">
<div className="col-lg-10 col-lg-offset-2">
<button
className="btn btn-primary"
onClick={this.handleUpdateUser}>
Update User Info
</button>
</div>
</div>
</form>
</section>
)
}
}
export default UserSettings
What is the expected behavior?
I don't expect to get that warning.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
React: 16.3.1
OS: Mac osSierra 10.12.6
Browser: Chrome
