1

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.

Aniket
  • 4,926
  • 12
  • 41
  • 54
  • Is the button component being rendered inside the same component as the component? Are you using a store hold state? – Ben Bud May 11 '16 at 21:51

3 Answers3

8

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: "" })
André Junges
  • 5,297
  • 3
  • 34
  • 48
2

Try reset field after setState:

this.setState({emailValue : ''});
this.refs.email.reset()

Also you can reset all form.

this.refs.form.reset()
Yurii Kramarenko
  • 1,025
  • 6
  • 16
0
const formRefdeposit = useRef(null);

<Formsy
        onValidSubmit={handleSubmit}
        onValid={enableButton}
        onInvalid={disableButton}
        ref={formRef}
 >
....Form Fields
</Formsy>

if you have class in your js file then use

this.formRef.current.reset(); 

if without class then use

formRef.current.reset();