React FormIk reset values to empty values handleReset function

Viewed 4982

I have a form which loads with default values.

I want a button to reset all form's values to empty values.

The built in handleReset function only resets the values to the default values that the form was loaded with. I tried to change the props with default values with concept similar to the code below, but the props are "read only".

resetToEmpty(){
   this.props.user = {};
}
<button type="button" onClick={ resetToEmpty}>Clear form demo data</button>

Code sand box https://x7069jq8lz.codesandbox.io/

How could reset all formIk fields to empty values?

Thanks!

2 Answers

The code sand box is broken, but i think you should consider to change your props to empty in state above, and just add 'enableReinitializing' prop to your Formik instance.

Then after getting new props your initialValues in Formik should be updated.

You have to pass an empty user to your form component again. So you'll have to bubble up the reset event, that is, send it to form's parent component where you initially passed the user object.

Let's say that when you click the Reset button you'll have to do this where you're setting the user initially. As it's being passed as a prop to formik this should go in your parent component. Something like this:

user: { name: '', age: '', gender: null }
Related