React Formik MUI Reusable Component SignUp Form

React Formik MUI Reusable Component SignUp Form

·

3 min read

React Formik is a library that makes it easier to work with forms in React applications. Material-UI (MUI) is a popular React component library for creating beautiful user interfaces. Together, they can be used to create reusable component forms.

To create a reusable component form with Formik and MUI, you can follow these steps:

  1. Define the form fields: Start by defining the form fields that will be used in the form. This can be done using standard HTML form elements or MUI components.

  2. Create a Formik form: Use the Formik library to create a form with validation and error handling. This will involve defining a schema that describes the shape of the data that will be submitted and creating a Formik component that wraps the form fields.

  3. Add MUI components: Use MUI components to style and lay out the form fields. You can also use MUI components for things like buttons and form helpers.

  4. Make the form component reusable: Finally, create a reusable form component that can be used throughout your application. This can be done by passing in props that define the form fields and validation schema and using them to dynamically generate the form.

Here is an example of what a reusable component form with Formik and MUI might look like:

interface FormikFieldProps {
  name: string;
  label: string;
  required?: boolean;
  mychecked?:boolean;
  fullWidth?:boolean;
}

const FormikCheckbox: React.FC<FormikFieldProps> = ({  fullWidth=false,  required = false , mychecked, ...props}) => {
  const {label = ""} = {...props}
  const [field, meta, helper ] = useField(props.name)
  const { touched, error } = meta
  const { setValue } = helper
  const { name, value } = field
  const isError = touched && error && true
  function renderHelperText() {
    if (meta.touched && meta.error) {
      return <FormHelperText error>{meta.error}</FormHelperText>
    }
  }
  return (
    <FormControl >
    {/* <FormLabel component="legend">Demo </FormLabel> */}
    {/* <FormGroup > */}
      <FormControlLabel
        control={
          <Checkbox 
          checked={mychecked}        
          name={name}
           />
        }
        {...field}
        {...props}
        label={label}
      />

    {/* </FormGroup> */}
    {renderHelperText()}
  </FormControl>
  );
};
export default FormikCheckbox;

And Reusdable Code will be like this

const FormValue3 = {
    check1 : false,
    check2 : false,  
}
const validationSchema = Yup.object().shape({
    check1: Yup.bool().oneOf([true], 'Required'),

  })



const submitForm = async (
    values: FormikValues,
    actions: FormikValues
  ): Promise<void> => {
    await sleep(1000);
    // alert(JSON.stringify(values, null, 2));
    console.log(values, "value")
    actions.setSubmitting(false);
    // actions.resetForm({values:""});
  };


  return (
    <div className="App">
      <h1>Sign Up</h1>
      <Formik
        initialValues={FormValue3}
        onSubmit={submitForm}
        validationSchema={validationSchema }
      >
        {({ dirty, isValid, isSubmitting, errors, touched, values, setFieldValue,  }) => {
          return (
            <div>
            <Form>
              <FormGroup>
              <FormikCheckbox
                name="all"
                label="All"
                id="all"
                mychecked={Object.keys(values).filter((key) => values[key] === false).length <1 }
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                  setFieldValue("check1", e.target.checked);
                  setFieldValue("check2", e.target.checked);
                  setFieldValue("other", e.target.checked);
                  setOpen(true)
                }}
              />

                 {Object.keys(FormValue3).map((item, key) => (
                 <FormikCheckbox
                 name={item}
                //  id={key}
                 key={key}
                 label={item}
                 mychecked={values[item] === true}                 
                 />                
                 ))}

              <Button
                variant="contained"
                color="primary"
                disabled={isSubmitting}
                // disabled ={!isValid || !dirty}
                type="submit"
                size="large"
                style={{ width: "400px" }}
              >
                Submit {isSubmitting && <CircularProgress />}
              </Button>
              </FormGroup>
            </Form>
            </div>
          );
        }}
      </Formik>
    </div>
  );
}

In this example, the validationSchema defines the shape of the data that will be submitted, and the ReusableForm component takes in initialValues and onSubmit props to make it reusable. The Field component is used to generate form fields based on the name property, and the as property is used to specify which MUI component to use to render the field. Finally, the Button component is used for the submit button, and the formik.isValid property is used to disable the button until the form is valid.

With this reusable component form, you can easily create forms throughout your application by passing in props that define the form fields and validation schema. This can help to reduce code duplication and make your forms more consistent and maintainable.

You can get Full Code Here

https://github.com/alamjamal/formik_reusable_form