How to use Material-ui@next TextField error props

Ras picture Ras · Mar 22, 2018 · Viewed 30.5k times · Source

I want to use Material-UI Next textfield error props link, the props type is boolean. The previous version of Material-UI props name is errorText and the props type is node link.

Textfield Material-UI previous version using errorText props :

<TextField
  name='name'
  floatingLabelText='Name'
  hintText='Type your name'
  value={this.state.fields.name}
  onChange={this.onChange}
  errorText={this.state.error}
/>

With errorText in Material-UI previous version, the code works good for displaying an error state.

Textfield Material-UI Next using error props:

<TextField
  name='name'
  label='Name'
  placeholder='Type your name'
  value={this.state.fields.name}
  onChange={this.onChange}
  error={true} //only accept true or false value
/>

On Material-UI Next errorText props changed to error with boolean type and only accept true or false value. If i set the error props to true, the textfield displaying error state at any time. I just want to displaying error state under certain conditions.

How can i use error state this.state.error on Material-UI Next textfield?

Answer

galah92 picture galah92 · Mar 22, 2018

Using a react component state, one can store the TextField value and use that as an indicator for an error. Material-UI exposes the error and helperText props to display an error interactively.

Take a look at the following example:

<TextField
  value={this.state.text}
  onChange={event => this.setState({ text: event.target.value })}
  error={text === ""}
  helperText={text === "" ? 'Empty field!' : ' '}
/>