bmvantunes / youtube-2020-june-multi-step-form-formik

A repository with a multi-step form using Formik, Yup and Material-UI
https://youtu.be/l3NEC4McW3g
MIT License
100 stars 68 forks source link

How to use FormikStep inside a component within a FormikStepper #10

Open ossiozac opened 3 years ago

ossiozac commented 3 years ago

Hi,

Thanks for the wonderful video and for providing all the code.

I am creating a site and would like to make FormikSteps within component so I can reuse them and make sure I keep the code DRY.

The problem I am having is when calling the component which returns a FormikStep inside a FormikStepper, the label and validationSchema don't exist on the parent, therefore the FormikStepper cannot access them.

Please see some example code:

MyForm.js

export default function MyForm() {
  const classes = useStyles();

  return (
      <Box p={2}>
        <FormikStepper
          initialValues={{ name: "" }}
          onSubmit={(values, actions) => {
            actions.setSubmitting(false);
            console.log(values);
          }}
        >

          <ReusableStep />

        </FormikStepper>
      </Box>
  );
}

ReusableStep.js

export default function ReusableStep() {

  return (
    <FormikStep
      label="Reusable Form Step"
      validationSchema={Yup.object({})}
    >

              <Grid item xs={12} sm={true}>

                <Field
                  component={TextField}
                  type="text"
                  name="name"
                  label="Name"
                  fullWidth
                />

              </Grid>
    <FormikStep />
  )
}

When in the current state, the validation doesn't work, and the Material UI Step doesn't get a label.

The only way I can get it to work is by passing validationSchema and label to the ReusableStep:

<ReusableStep 
      label="Reusable Form Step"
      validationSchema={Yup.object({})}
/>

This is not great, as I would have to repeat defining the schema each time I want to use the FormikStep.

Please could you help me get this sorted?

Many thanks, Zac

ossiozac commented 3 years ago

I'd just like to add that ReusableStep will not be reused in the same form. It will be reused on another form on another page.

That's why the label is hard coded within it, and not passed as a prop into it.

Thanks

khrukawa commented 1 year ago

Hi Thank you for this.And I want to add Autocomplete in this project.But I can't .Please help me. `

export default function Threenumber() { const [addtocart] = useAddToCartMutation(); const [title, setTitle] = useState([]); const { data } = useTakeThreeDateQuery(); const [cityId, setCityId] = useState({ city_id: "" });

return (

3D } label="Test Label" /> { await sleep(3000); console.log("values", values); console.log("states", cityId.city_id); }} > String(option.value)} fullWidth style={{ marginTop: "25px" }} renderInput={(params) => ( )} />

); }

export interface FormikStepProps extends Pick<FormikConfig, "children" | "validationSchema"> { label: string; }

export function FormikStep({ children }: FormikStepProps) { return <>{children}</>; }

export function FormikStepper({ children, ...props }: FormikConfig) { const childrenArray = React.Children.toArray( children ) as React.ReactElement[]; const [step, setStep] = useState(0); const currentChild = childrenArray[step]; const [completed, setCompleted] = useState(false);

function isLastStep() { return step === childrenArray.length - 1; }

return ( <Formik {...props} validationSchema={currentChild.props.validationSchema} onSubmit={async (values, helpers) => { if (isLastStep()) { await props.onSubmit(values, helpers); setCompleted(true); } else { setStep((s) => s + 1); helpers.setTouched({}); } }}

{({ isSubmitting}) => (

{childrenArray.map((child, index) => ( index || completed} {child.props.label} ))}
      {currentChild}

      <Grid container spacing={2}>
        {step > 0 ? (
          <Grid item>
            <Button
              disabled={isSubmitting}
              variant="contained"
              color="primary"
              onClick={() => setStep((s) => s - 1)}
            >
              Back
            </Button>
          </Grid>
        ) : null}
        <Grid item>
          <Button
            startIcon={
              isSubmitting ? <CircularProgress size="1rem" /> : null
            }
            disabled={isSubmitting}
            variant="contained"
            color="primary"
            type="submit"
          >
            {isSubmitting ? "Submitting" : isLastStep() ? "Submit" : "Next"}
          </Button>
        </Grid>
      </Grid>
    </Form>
  )}
</Formik>

); } `