25
votes

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?

2

2 Answers

42
votes

Reason is, you didn't define the phone in state variable so on initial rendering TextField will be treated as uncontrolled component because value property will have undefined value.

In this line

value = {this.state.phone} => this.state.phone is undefined initially

To fix this define phone in state variable, like this:

constructor(props) {
    super(props)
    this.state = { 
        errorText: '', 
        value:this.props, 
        phone: '' 
    }
}

Or define the value property by using Short-circuit evaluation like this:

value = {this.state.phone || ''}      //(undefined || '') = ''
9
votes

Because your value is undefined that's why you are getting this error

Try this

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>
    )
  }