I am getting this error below.
Warning: TextField is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
I am using material-ui.
Here is my code:
class RegistrationForm extends React.Component{
constructor(props) {
super(props)
this.state = { errorText: '', value:this.props }
}
phone(event) {
var strRegExpMobile=/^\d{10}$/;
if (event.target.value.match(strRegExpMobile)) {
this.setState({ errorText: '',
phone:event.target.value
})
} else {
this.setState({ errorText: 'Invalid format' })
}
}
handleSubmit(event){
alert("submit");
var data={
phone:this.state.phone
}
console.log(data)
}
render() {
return (
<div>
<TextField hintText="Phone"
floatingLabelText="Phone"
name="phone"
value={this.state.phone}
errorText= {this.state.errorText}
onChange={this.phone.bind(this)}/>
<RaisedButton label="Submit"
primary={true}
onClick={this.handleSubmit.bind(this)}/>
</div>
)
}
}
Can any one tell where I am wrong?
Best Answer
Reason is, you didn't define the
phone
instate
variable so on initial rendering TextField will be treated as uncontrolled component because value property will haveundefined
value.In this line
value = {this.state.phone}
=> this.state.phone is undefined initiallyTo fix this define phone in state variable, like this:
Or define the value property by using Short-circuit evaluation like this: