'How disable validation Formik when clicking cancel button?

I'm using Material-ui with Formik and Yup for form validation, but I'm having trouble disabling form validation when clicking the cancel button. Tried using formik resetForm but it doesn't work! Can you help me?

By clicking the cancel button, it's doesn't work! enter image description here

Thank you for your help!

Code

import { Box, Button, Grid } from "@mui/material";
import { Field, Form, Formik } from "formik";
import * as Yup from "yup";
import { makeStyles } from "@mui/styles";

import "./styles.css";
import { InputText } from "./component/InputText";
import { useState } from "react";

const useStyles = makeStyles(() => ({
  buttonsContainer: {
    display: "flex",
    flex: "0 0 auto",
    justifyContent: "center",
    width: "100%",
    height: "100%",
    marginTop: 8
  }
}));

const initialValues = {
  movie: ""
};

const validationSchema = Yup.object().shape({
  movie: Yup.string().required("Required")
});

export default function App() {
  const classes = useStyles();
  const [addMovie, setAddMovie] = useState(false);

  function _onSubmit(fields, { props, setErrors, setSubmitting }) {
    console.log(fields);
    setSubmitting(false);
    setAddMovie(false);
  }

  return (
    <Box className="App">
      <h1>Validation schema with Formik and Yup</h1>
      <h2>How disable validation Formik when clicking cancel button?</h2>
      <Formik
        enableReinitialize={true}
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={_onSubmit}
      >
        {function Render({
          errors,
          touched,
          isSubmitting,
          setFieldValue,
          handleChange,
          resetForm,
          setErrors
        }) {
          return (
            <>
              {addMovie ? (
                <Box display="flex" alignItems="center" justifyContent="center">
                  <Form
                    id="form"
                    style={{
                      border: "1px solid gray",
                      padding: 16,
                      paddingBottom: 32
                    }}
                    maxWidth="500px"
                  >
                    <Grid container direction="row">
                      <Grid item xs={12}>
                        <h2>Form</h2>
                      </Grid>
                      <Grid item xs={12}>
                        <Field
                          name="movie"
                          component={InputText}
                          label="Movie"
                          autoFocus
                          disabled={isSubmitting}
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <Box className={classes.buttonsContainer}>
                          <Box display="flex" alignItems="center">
                            <Box mr={2}>
                              <Button
                                variant="contained"
                                color="primary"
                                fullWidth
                                type="submit"
                                form="form"
                                disabled={isSubmitting}
                              >
                                Submit
                              </Button>
                            </Box>
                            <Button
                              fullWidth
                              variant="outlined"
                              disabled={isSubmitting}
                              onClick={() => {
                                resetForm();
                                setAddMovie(false);
                              }}
                            >
                              Cancel
                            </Button>
                          </Box>
                        </Box>
                      </Grid>
                    </Grid>
                  </Form>
                </Box>
              ) : (
                <Grid container direction="row">
                  <Grid item xs={12}>
                    <Box className={classes.buttonsContainer}>
                      <Box display="flex" alignItems="center">
                        <Box mr={2}>
                          <Button
                            variant="contained"
                            color="primary"
                            fullWidth
                            disabled={isSubmitting}
                            onClick={() => {
                              setAddMovie(true);
                            }}
                          >
                            Add Movie
                          </Button>
                        </Box>
                      </Box>
                    </Box>
                  </Grid>
                </Grid>
              )}
            </>
          );
        }}
      </Formik>
    </Box>
  );
}


Solution 1:[1]

I had the same problem and it is caused by the autofocus prop on your Field. Turns out that the field validation intercepts the event to leave the form since it considers that the form isn't untouched (you technically selected a field). I haven't found a workaround this yet but you could look into using the pristine prop from Formik. Hope this helps!

<Formik
    enableReinitialize={true}
    initialValues={initialValues}
    validationSchema={validationSchema}
    onSubmit={_onSubmit}
  >
    {({
      errors,
      touched,
      pristine
      isSubmitting,
      setFieldValue,
      handleChange,
      resetForm,
      setErrors
    }) => (
       <Form>
         <Field
           name="movie"
           component={InputText}
           label="Movie"
           disabled={isSubmitting}
         />
       </Form>
    )}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Antoine Lessard