Search code examples
reactjsformikyup

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

  • I solved it by passing validateOnBlur={false} to Formik.

    Before:

    Before solved

    After:

    After soved

    <Formik
            enableReinitialize={true}
            validateOnBlur={false}
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={_onSubmit}
     >