1
votes

Getting error while using material ui textfield

Warning: TextField is changing a controlled input of type text 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


export default class GoogleAutoComplete extends Component {
  render() {
    return (
        <TextField
          ref={(c) => this._input = c}
          //errorText={this.state.errorText}
          onChange={this.onChangeInput.bind(this)}
          name={this.props.name}
          placeholder='Search Location'
          style={{width:'100%'}}
          id={this.props.id}
          value={this.state.location}
        />
     )
  }
}
4

4 Answers

4
votes

The solution for the issue is to remove the value attribute in textfield component or put null value in value attribute of component. Because the reactjs differentiates controlled and uncontrolled component. Kindly find the below code.

render() {
    return (
        <TextField
          ref={(c) => this._input = c}
          //errorText={this.state.errorText}
          onChange={this.onChangeInput.bind(this)}
          name={this.props.name}
          placeholder='Search Location'
          style={{width:'100%'}}
          id={this.props.id}
          value={this.state.location || ''}
        />
     )
  }
}
1
votes

This error happen when the value prop of you TexField element is null or undefined.

quick and dirty solution :

<TextField
      ref={(c) => this._input = c}
      // ...
      value={this.state.location || ''}
    />

Tips : it is better to never set state.location to null nor undefined, check your componentWillMount method. To keep React in sync with your data, you should keep your input controlled.

0
votes

Uncontrolled Textfield does not refer to your component directly, but to the Textfield that is defined in your component.

React differentiates between controlled and uncontrolled components:

An <Textfield> without a value property is an uncontrolled component
0
votes

Until your state.location is defined, you are passing undefined to the value prop of the text field. By definition, a TextField without a value property is considered uncontrolled. This may be happening on the 'first' time passing through the render function.

You can fix this by setting your value thusly: value={this.props.value?this.props.value:""} This will ensure your TextField component is controlled the entire time, while still having it be 'empty' on the first render pass.