reactjsmaterial-uiformsy-material-uiformsy-react

How to clear the text field in formsy material ui React


Hi I am using React 14 and writing it in ES6. I am using formsy-material-ui for form validations. There is a scenario where I want to clear the value of text field on click of a button.

I tried the following code

<FormsyText
    name="email"
    ref="email"
    validations="isEmail"
    validationError="Invalid Email"
    hintText="Email"
    value={this.state.emailValue}
/>

And on click of the button, I am executing the following line of code

this.setState({emailValue : ''});

But the text field is not getting cleared. How to clear it. Pls help.


Solution

  • So, if you were using a controlled input (maybe using directly the TextField from Material-ui) - your code would be right, however the FormsyText component handle it's value internally.
    If you pass a value or defaultValue it'll just be used when it's rendered, you can check it here.

    I only see one way to clear the value now, in an imperative style.

    this.refs.email.setState({ value: "" })
    

    Note: I suggest you to change the way you're using the ref. Using refs with a string is deprecated and probably will be removed in the future. Instead you should pass a function that's gonna receive that component. https://facebook.github.io/react/docs/more-about-refs.html
    Example:

    <FormsyText
        name="email"
        ref={(node) => this._emailText = node}
        validations="isEmail"
        validationError="Invalid Email"
        hintText="Email"
        value={this.state.emailValue}
    />
    //And to clear it
    this._emailText.setState({ value: "" })