formik#Form TypeScript Examples

The following examples show how to use formik#Form. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: login.component.tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
LoginComponent: React.FunctionComponent<Props> = props => {
  const { onLogin } = props;

  return (
    <Card>
      <CardHeader title="Login" />
      <CardContent>
        <Formik
          onSubmit={onLogin}
          initialValues={createEmptyLogin()}
          validate={formValidation.validateForm}
        >
          {() => (
            <Form>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                }}
              >
                <TextFieldComponent name="user" label="Name" />
                <TextFieldComponent
                  name="password"
                  label="Password"
                  type="password"
                />
                <Button type="submit" variant="contained" color="primary">
                  Login
                </Button>
              </div>
            </Form>
          )}
        </Formik>
      </CardContent>
    </Card>
  );
}
Example #2
Source File: CommentForm.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
CommentForm: React.FC<CommentFormProps> = ({ transactionId, transactionComment }) => {
  const classes = useStyles();
  const initialValues = { content: "" };

  return (
    <div>
      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={(values, { setSubmitting }) => {
          setSubmitting(true);
          transactionComment({ transactionId, ...values });
        }}
      >
        {() => (
          <Form className={classes.form}>
            <Field name="content">
              {({ field, meta }: FieldProps) => (
                <TextField
                  variant="outlined"
                  margin="dense"
                  fullWidth
                  id={`transaction-comment-input-${transactionId}`}
                  type="text"
                  placeholder="Write a comment..."
                  inputProps={{ "data-test": `transaction-comment-input-${transactionId}` }}
                  error={meta.touched && Boolean(meta.error)}
                  helperText={meta.touched ? meta.error : ""}
                  {...field}
                />
              )}
            </Field>
          </Form>
        )}
      </Formik>
    </div>
  );
}
Example #3
Source File: ParametersForm.stories.tsx    From panvala with Apache License 2.0 6 votes vote down vote up
storiesOf('ParametersForm', module).add('ParametersForm', () => (
  <StoryWrapper>
    <Box width="620px">
      <Formik initialValues={parameters} onSubmit={noop}>
        {() => (
          <Form>
            <ParametersForm
              onChange={(name: string, value: any) => {
                console.log('name, value:', name, value);
              }}
              parameters={parameters}
            />
          </Form>
        )}
      </Formik>
    </Box>
  </StoryWrapper>
));
Example #4
Source File: SQFormReadOnly.tsx    From SQForm with MIT License 6 votes vote down vote up
function SQFormReadOnly<Values extends FormikValues>({
  readOnlyFields,
  initialValues,
  enableReinitialize = false,
  muiGridProps = {},
}: SQFormReadOnlyProps<Values>): JSX.Element {
  return (
    <Formik<Values>
      initialValues={initialValues}
      onSubmit={noop}
      enableReinitialize={enableReinitialize}
    >
      {(_props) => {
        return (
          <Form>
            <Grid
              {...muiGridProps}
              container
              spacing={muiGridProps.spacing ?? 2}
            >
              {readOnlyFields.map((readOnlyField, index) => {
                const props = {
                  key: readOnlyField?.key ?? index,
                  muiFieldProps: noBottomMarginStyle,
                  ...readOnlyField,
                };

                if (readOnlyField?.mask) {
                  return <SQFormMaskedReadOnlyField {...props} />;
                }
                return <SQFormReadOnlyField {...props} />;
              })}
            </Grid>
          </Form>
        );
      }}
    </Formik>
  );
}
Example #5
Source File: MultiStateToggleField.stories.tsx    From amplication with Apache License 2.0 6 votes vote down vote up
Default = (props: any) => {
  return (
    <Formik
      initialValues={{ multiStateFieldName: "Yellow" }}
      onSubmit={() => {}}
    >
      <Form>
        <MultiStateToggleField
          label=""
          name="multiStateFieldName"
          options={OPTIONS}
        />
      </Form>
    </Formik>
  );
}
Example #6
Source File: index.tsx    From formik-material-ui with MIT License 6 votes vote down vote up
App: React.FC = () => {
  const handleSubmit = (values: FormValues): void => {
    alert(JSON.stringify(values));
  };

  return (
    <div className="App">
      <h1>Sign Up</h1>
      <Formik
        initialValues={initialValues}
        onSubmit={handleSubmit}
        validationSchema={SignupSchema}
      >
        {({ dirty, isValid }) => {
          return (
            <Form>
              <FormikField name="name" label="Name" required />
              <FormikSelect
                name="position"
                items={positionItems}
                label="Position"
                required
              />

              <Button
                variant="contained"
                color="primary"
                disabled={!dirty || !isValid}
                type="submit"
              >
                Primary
              </Button>
            </Form>
          );
        }}
      </Formik>
    </div>
  );
}
Example #7
Source File: address-field.test.tsx    From openmrs-esm-patient-registration with MIT License 6 votes vote down vote up
describe('address field', () => {
  it('renders input fields matching addressTemplate config', async () => {
    const { findByLabelText } = render(
      <ResourcesContext.Provider value={{ addressTemplate: mockResponse } as Resources}>
        <Formik initialValues={{}} onSubmit={null}>
          <Form>
            <AddressField />
          </Form>
        </Formik>
      </ResourcesContext.Provider>,
    );

    const postalCode = await findByLabelText('Location.postalCode');
    const address1 = await findByLabelText('Location.address1');
    const country = await findByLabelText('Location.country');
    const stateProvince = await findByLabelText('Location.stateProvince');
    const cityVillage = await findByLabelText('Location.cityVillage');

    expect(postalCode).toBeInTheDocument();
    expect(address1).toBeInTheDocument();
    expect(country).toBeInTheDocument();
    expect(stateProvince).toBeInTheDocument();
    expect(cityVillage).toBeInTheDocument();
  });
});
Example #8
Source File: RuleForm.tsx    From netify with BSD 2-Clause "Simplified" License 6 votes vote down vote up
RuleForm = memo<RuleFormProps>(function RuleForm({initialRule, onSave, onCancel}) {
	const initialValues = useMemo(() => serializeRuleForm(initialRule), [initialRule]);

	const handleSubmit = useCallback(
		(rawValue: RuleFormSchema) => {
			const value = deserializeRuleForm(rawValue, initialRule.id, initialRule.active);
			onSave(value);
		},
		[initialRule.id, initialRule.active, onSave],
	);

	const form = useFormik<RuleFormSchema>({
		initialValues,
		validateOnBlur: true,
		validateOnChange: false,
		validationSchema: ruleFormSchema,
		onSubmit: handleSubmit,
	});

	return (
		<div className={styles.root}>
			<FormikProvider value={form}>
				<Form className={styles.form}>
					<RuleLabel />
					<RuleFilter />
					<RuleActionSwitcher />
					<div className={styles.config}>
						<RuleActionConfig />
					</div>

					<div className={styles.controls}>
						<Button className={styles.saveButton} styleType='dark' type='submit'>
							Save
						</Button>
						<Button onClick={onCancel}>Cancel</Button>
					</div>
				</Form>
			</FormikProvider>
		</div>
	);
})
Example #9
Source File: login.form.component.tsx    From MyWay-client with MIT License 6 votes vote down vote up
LoginForm = observer(function LoginForm() {
  const router = useRouter();
  const { userStore } = useStores();

  return (
    <Formik
      initialValues={{
        email: "",
        password: "",
      }}
      onSubmit={(values, { setSubmitting, setStatus }) => {
        userStore
          .login(values)
          .then(() => {
            setStatus({ message: "ההתחברות עברה בהצלחה." });
            setTimeout(() => router.push("/"), 2000);
          })
          .catch((e: APIErrorResponse) => {
            setStatus({ error: e.message });
          })
          .finally(() => setSubmitting(false));
      }}
      validationSchema={LoginSchema}
    >
      {({ isSubmitting, status }) => (
        <Form className="flex justify-center items-center flex-wrap w-96">
          <FormField name="email" type="email" placeholder="כתובת דוא״ל" />
          <ErrorMessage name="email" />

          <FormField name="password" type="password" placeholder="סיסמה" />
          <ErrorMessage name="password" />

          <StatusMessage formStatus={status} />
          <SubmitButton isSubmitting={isSubmitting} value="התחברות" />
        </Form>
      )}
    </Formik>
  );
})
Example #10
Source File: data.component.tsx    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
DataComponent: React.FunctionComponent<Props> = ({
  employee,
  className,
  onSave,
  isEditMode,
  onCancel,
}) => {
  React.useEffect(() => {
    const newValidationSchema = produce(validationSchema, darft => {
      darft.field.temporalPassword = isEditMode ? [] : [Validators.required];
    });
    formValidation.updateValidationSchema(newValidationSchema);
  }, [isEditMode]);

  return (
    <Formik
      initialValues={employee}
      enableReinitialize={true}
      onSubmit={onSave}
      validate={formValidation.validateForm}
    >
      {() => (
        <Form className={cx(classes.form({ isEditMode }), className)}>
          <TextFieldComponent
            label="Id"
            name="id"
            className={classes.id}
            InputProps={{
              readOnly: true,
            }}
          />
          {!isEditMode && (
            <TextFieldComponent
              label="Clave Temporal"
              name="temporalPassword"
              className={classes.temporalPassword}
            />
          )}
          <TextFieldComponent
            label="Nombre"
            name="name"
            className={classes.name}
          />
          <TextFieldComponent
            label="Email"
            name="email"
            className={classes.email}
          />
          <CheckboxComponent
            name="isActive"
            label="Activo"
            color="primary"
            className={classes.isActive}
          />
          <CommandFooterComponent
            onCancel={onCancel}
            className={classes.commands}
          />
        </Form>
      )}
    </Formik>
  );
}
Example #11
Source File: ChangeEmail.tsx    From abrechnung with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function ChangeEmail() {
    useTitle("Abrechnung - Change E-Mail");

    const handleSubmit = (values, { setSubmitting }) => {
        changeEmail({
            password: values.password,
            newEmail: values.newEmail,
        })
            .then((res) => {
                setSubmitting(false);
                toast.success("Requested email change, you should receive an email with a confirmation link soon");
            })
            .catch((error) => {
                setSubmitting(false);
                toast.error(error);
            });
    };

    return (
        <MobilePaper>
            <Typography component="h3" variant="h5">
                Change E-Mail
            </Typography>
            <Formik initialValues={{ password: "", newEmail: "" }} onSubmit={handleSubmit}>
                {({ values, handleChange, handleBlur, handleSubmit, isSubmitting }) => (
                    <Form>
                        <TextField
                            required
                            fullWidth
                            margin="normal"
                            autoFocus
                            type="password"
                            name="password"
                            variant="standard"
                            value={values.password}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            label="Password"
                        />

                        <TextField
                            required
                            fullWidth
                            margin="normal"
                            type="email"
                            name="newEmail"
                            variant="standard"
                            value={values.newEmail}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            label="New E-Mail"
                        />

                        {isSubmitting && <LinearProgress />}
                        <Button type="submit" color="primary" disabled={isSubmitting}>
                            Save
                        </Button>
                    </Form>
                )}
            </Formik>
        </MobilePaper>
    );
}
Example #12
Source File: SQForm.tsx    From SQForm with MIT License 5 votes vote down vote up
function SQForm<Values extends FormikValues>({
  children,
  enableReinitialize = false,
  initialValues,
  muiGridProps = {},
  onSubmit,
  validationSchema,
}: SQFormProps<Values>): JSX.Element {
  const initialErrors = useInitialRequiredErrors(
    validationSchema,
    initialValues
  );

  // HACK: This is a workaround for: https://github.com/mui-org/material-ui-pickers/issues/2112
  // Remove this reset handler when the issue is fixed.
  const handleReset = () => {
    document &&
      document.activeElement &&
      (document.activeElement as HTMLElement).blur();
  };

  const handleSubmit = useDebouncedCallback(
    (values: Values, formikHelpers: FormikHelpers<Values>) =>
      onSubmit(values, formikHelpers),
    500,
    {leading: true, trailing: false}
  );

  return (
    <Formik<Values>
      enableReinitialize={enableReinitialize}
      initialErrors={initialErrors}
      initialValues={initialValues}
      onSubmit={handleSubmit}
      onReset={handleReset}
      validationSchema={validationSchema}
      validateOnMount={true}
    >
      {(_props) => {
        return (
          <Form>
            <Grid
              {...muiGridProps}
              container
              spacing={muiGridProps.spacing ?? 2}
            >
              {children}
            </Grid>
          </Form>
        );
      }}
    </Formik>
  );
}
Example #13
Source File: ProfileForm.tsx    From amplication with Apache License 2.0 5 votes vote down vote up
ProfileForm = () => {
  const { data, error, refetch } = useQuery<TData>(GET_USER);

  const [updateAccount, { error: updateError }] = useMutation<TData>(
    UPDATE_ACCOUNT
  );

  const { trackEvent } = useTracking();

  const handleSubmit = useCallback(
    newData => {
      const { firstName, lastName } = newData;
      trackEvent({
        eventName: "updateAccountInfo"
      });
      updateAccount({
        variables: {
          data: {
            firstName,
            lastName
          }
        }
      })
        .then(() => refetch())
        .catch(console.error);
    },
    [trackEvent, updateAccount, refetch]
  );

  const errorMessage = formatError(error || updateError);

  return data ? (
    <div>
      <Formik
        initialValues={data.me.account}
        validate={(values: models.Account) => validate(values, FORM_SCHEMA)}
        enableReinitialize
        onSubmit={handleSubmit}>
        {formik => {
          return (
            <Form>
              <FormikAutoSave debounceMS={1000} />
              <TextField name='email' label='Email' disabled />
              <TextField name='firstName' label='First Name' />
              <TextField name='lastName' label='Last Name' />
            </Form>
          );
        }}
      </Formik>
      <Snackbar open={Boolean(error)} message={errorMessage} />
    </div>
  ) : null;
}
Example #14
Source File: index.tsx    From advanced-formik-validations-with-yup with MIT License 5 votes vote down vote up
App: React.FC = () => {
  const handleSubmit = (values: FormValues): void => {
    alert(JSON.stringify(values));
  };

  return (
    <div className="App">
      <h1>Sign Up</h1>
      <Formik
        initialValues={initialValues}
        onSubmit={handleSubmit}
        validationSchema={SignupSchema}
      >
        {({ dirty, isValid }) => {
          return (
            <Form>
              <FormikField name="name" label="Name" required />
              <FormikField name="email" label="Email" required />
              <FormikField
                name="password"
                label="Password"
                required
                type="password"
              />
              <FormikField
                name="passwordConfirm"
                label="Confirm Password"
                required
                type="password"
              />
              <FormikSelect
                name="position"
                items={positionItems}
                label="Position"
                required
              />

              <Button
                variant="contained"
                color="primary"
                disabled={!dirty || !isValid}
                type="submit"
              >
                Primary
              </Button>
            </Form>
          );
        }}
      </Formik>
    </div>
  );
}
Example #15
Source File: [token].tsx    From lireddit with MIT License 5 votes vote down vote up
ChangePassword: NextPage = () => {
  const router = useRouter();
  const [changePassword] = useChangePasswordMutation();
  const [tokenError, setTokenError] = useState("");
  return (
    <Wrapper variant="small">
      <Formik
        initialValues={{ newPassword: "" }}
        onSubmit={async (values, { setErrors }) => {
          const response = await changePassword({
            variables: {
              newPassword: values.newPassword,
              token:
                typeof router.query.token === "string"
                  ? router.query.token
                  : "",
            },
            update: (cache, { data }) => {
              cache.writeQuery<MeQuery>({
                query: MeDocument,
                data: {
                  __typename: "Query",
                  me: data?.changePassword.user,
                },
              });
            },
          });
          if (response.data?.changePassword.errors) {
            const errorMap = toErrorMap(response.data.changePassword.errors);
            if ("token" in errorMap) {
              setTokenError(errorMap.token);
            }
            setErrors(errorMap);
          } else if (response.data?.changePassword.user) {
            // worked
            router.push("/");
          }
        }}
      >
        {({ isSubmitting }) => (
          <Form>
            <InputField
              name="newPassword"
              placeholder="new password"
              label="New Password"
              type="password"
            />
            {tokenError ? (
              <Flex>
                <Box mr={2} style={{ color: "red" }}>
                  {tokenError}
                </Box>
                <NextLink href="/forgot-password">
                  <Link>click here to get a new one</Link>
                </NextLink>
              </Flex>
            ) : null}
            <Button
              mt={4}
              type="submit"
              isLoading={isSubmitting}
              variantColor="teal"
            >
              change password
            </Button>
          </Form>
        )}
      </Formik>
    </Wrapper>
  );
}
Example #16
Source File: index.tsx    From youtube-2020-june-material-ui-themes with MIT License 5 votes vote down vote up
export function FormikStepper({
  children,
  ...props
}: FormikConfig<FormikValues>) {
  const childrenArray = React.Children.toArray(children) as React.ReactElement<
    FormikStepProps
  >[];
  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);
        }
      }}
    >
      {({ isSubmitting }) => (
        <Form autoComplete="off">
          <Stepper alternativeLabel activeStep={step}>
            {childrenArray.map((child, index) => (
              <Step
                key={child.props.label}
                completed={step > index || completed}
              >
                <StepLabel>{child.props.label}</StepLabel>
              </Step>
            ))}
          </Stepper>

          {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 xs={12}>
              <Button
                startIcon={
                  isSubmitting ? <CircularProgress size="1rem" /> : null
                }
                disabled={isSubmitting}
                type="submit"
                fullWidth
              >
                {isSubmitting ? "Submitting" : isLastStep() ? "Submit" : "NeXt"}
              </Button>
            </Grid>
          </Grid>
        </Form>
      )}
    </Formik>
  );
}
Example #17
Source File: index.tsx    From youtube-2020-june-multi-step-form-formik with MIT License 5 votes vote down vote up
export function FormikStepper({ children, ...props }: FormikConfig<FormikValues>) {
  const childrenArray = React.Children.toArray(children) as React.ReactElement<FormikStepProps>[];
  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);

          // the next line was not covered in the youtube video
          //
          // If you have multiple fields on the same step
          // we will see they show the validation error all at the same time after the first step!
          //
          // If you want to keep that behaviour, then, comment the next line :)
          // If you want the second/third/fourth/etc steps with the same behaviour
          //    as the first step regarding validation errors, then the next line is for you! =)
          //
          // In the example of the video, it doesn't make any difference, because we only
          //    have one field with validation in the second step :)
          helpers.setTouched({});
        }
      }}
    >
      {({ isSubmitting }) => (
        <Form autoComplete="off">
          <Stepper alternativeLabel activeStep={step}>
            {childrenArray.map((child, index) => (
              <Step key={child.props.label} completed={step > index || completed}>
                <StepLabel>{child.props.label}</StepLabel>
              </Step>
            ))}
          </Stepper>

          {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>
  );
}
Example #18
Source File: Governance.tsx    From homebase-app with MIT License 5 votes vote down vote up
Governance: React.FC = () => {
  const { dispatch, state, updateCache } = useContext(CreatorContext);
  const { votingSettings } = state.data;
  const history = useHistory();

  const saveStepInfo = (
    values: VotingSettings,
    { setSubmitting }: { setSubmitting: (b: boolean) => void }
  ) => {
    const newState = {
      ...state.data,
      votingSettings: values,
    };
    updateCache(newState);
    setSubmitting(true);
    dispatch({ type: ActionTypes.UPDATE_VOTING_SETTINGS, voting: values });
    history.push(`quorum`);
  };

  return (
    <Box maxWidth={950}>
      <Grid container direction="row" justify="space-between">
        <Grid item xs={12}>
          <Typography variant="h3" color="textSecondary">
            Proposals & Voting
          </Typography>
        </Grid>
      </Grid>
      <Grid container direction="row">
        <Grid item xs={12}>
          <CustomTypography variant="subtitle1" color="textSecondary">
            These settings will define the duration, support and approval
            required for proposals.
          </CustomTypography>
        </Grid>
      </Grid>

      <Formik
        enableReinitialize
        validate={validateForm}
        onSubmit={saveStepInfo}
        initialValues={votingSettings}
      >
        {({
          submitForm,
          isSubmitting,
          setFieldValue,
          values,
          errors,
          touched,
        }) => {
          return (
            <Form style={{ width: "100%" }}>
              <GovernanceForm
                submitForm={submitForm}
                isSubmitting={isSubmitting}
                setFieldValue={setFieldValue}
                errors={errors}
                touched={touched}
                values={values}
              />
            </Form>
          );
        }}
      </Formik>
    </Box>
  );
}
Example #19
Source File: index.tsx    From Mokku with MIT License 5 votes vote down vote up
StyledForm = styled(Form)`
  padding: 8px 16px;
  width: 656px;
`
Example #20
Source File: input.test.tsx    From openmrs-esm-patient-registration with MIT License 5 votes vote down vote up
describe.skip('checkbox input', () => {
  const setupInput = async () => {
    render(
      <Formik initialValues={{ checkbox: false }} onSubmit={null}>
        <Form>
          <Input id="checkbox" labelText="checkbox" name="checkbox" light />
        </Form>
      </Formik>,
    );
    return screen.getByLabelText('checkbox') as HTMLInputElement;
  };

  it('exists', async () => {
    const input = await setupInput();
    expect(input.type).toEqual('checkbox');
  });

  it('can input data', async () => {
    const input = await setupInput();
    const expected = true;

    fireEvent.click(input);
    fireEvent.blur(input);

    await wait();

    expect(input.checked).toEqual(expected);
  });

  it('can update data', async () => {
    const input = await setupInput();
    const expected = false;

    fireEvent.click(input);
    fireEvent.blur(input);

    fireEvent.click(input);
    fireEvent.blur(input);

    await wait();

    expect(input.checked).toEqual(expected);
  });
});
Example #21
Source File: LoginForm.tsx    From querybook with Apache License 2.0 5 votes vote down vote up
LoginForm: React.FunctionComponent<ILoginFormProps> = ({
    onSuccessLogin,
}) => {
    const [errorMessage, setErrorMessage] = React.useState<string>(null);
    return (
        <Formik
            initialValues={{
                username: '',
                password: '',
            }}
            onSubmit={({ username, password }) =>
                UserResource.login(username, password).then(
                    onSuccessLogin,
                    (error) => setErrorMessage(String(error))
                )
            }
        >
            {({ handleSubmit, isSubmitting, isValid }) => {
                const usernameField = (
                    <SimpleField type="input" name="username" />
                );

                const passwordField = (
                    <SimpleField
                        type="input"
                        name="password"
                        inputType="password"
                    />
                );

                const errorMessageDOM = errorMessage && (
                    <Message message={errorMessage} type="error" />
                );
                const loginButton = (
                    <Button
                        onClick={() => handleSubmit()}
                        title="Login"
                        disabled={isSubmitting || !isValid}
                    />
                );

                return (
                    <FormWrapper className="LoginForm" minLabelWidth="150px">
                        <Form>
                            {usernameField}
                            {passwordField}
                            {errorMessageDOM}
                            <br />
                            <div className="center-align">{loginButton}</div>
                        </Form>
                    </FormWrapper>
                );
            }}
        </Formik>
    );
}
Example #22
Source File: GenericForm.tsx    From frontend with MIT License 5 votes vote down vote up
export default function GenericForm<T>({ children, ...formProps }: GenericFormProps<T>) {
  return (
    <Formik<T> {...formProps}>
      <Form>{children}</Form>
    </Formik>
  )
}
Example #23
Source File: request.tsx    From rcvr-app with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function PasswordResetRequestPage() {
  const { t } = usePageLocale('business/password-reset/request')
  const [loading, setLoading] = React.useState(false)
  const [done, setDone] = React.useState(false)

  const handleSubmit = async ({ email }) => {
    setLoading(true)

    await postRequestPasswordReset(email)

    setDone(true)
    setLoading(false)
  }

  const EmailSchema = Yup.object().shape({
    email: Yup.string().required(t('emailRequired')),
  })

  return (
    <MobileApp pageTitle={t('pageTitle')} logoVariant="big">
      <Text as="h2" variant="h2">
        {t('pageHeadline')}
      </Text>
      <Box height={4} />
      <Text>
        <p>{t('pageExplanation')}</p>
      </Text>
      <Box height={4} />

      {!done && (
        <Formik
          initialValues={{ email: '' }}
          validationSchema={EmailSchema}
          onSubmit={handleSubmit}
        >
          <Card variant="form" mx={-4}>
            <Loading show={loading} />
            <Form>
              <Input name="email" label="Email" autoComplete="email" />
              <Box height={5} />
              <Button type="submit" css={{ width: '100%' }}>
                {t('resetPasswordButtonText')}
              </Button>
            </Form>
          </Card>
        </Formik>
      )}
      {done && (
        <Callout>
          <Text>
            {t('doneMessage')}
            <RecoverTeamEmailLink>{t('support')}</RecoverTeamEmailLink>.
          </Text>
        </Callout>
      )}

      <Row justifyContent="center" my={6}>
        <Link href="/business/login" as="a" passHref>
          <Text variant="link">{t('goToLoginLinkText')}</Text>
        </Link>
      </Row>
    </MobileApp>
  )
}
Example #24
Source File: index.tsx    From synapse-extension with MIT License 5 votes vote down vote up
innerForm = (props: any) => {
  const intl = useIntl();

  const { values, touched, errors, isSubmitting, handleChange, handleBlur, handleSubmit } = props;

  return (
    <Form
      className="export-mnemonic-key"
      id="export-mnemonic-key"
      onSubmit={handleSubmit}
      aria-label="form"
    >
      <TextField
        size="small"
        label={intl.formatMessage({ id: 'Password' })}
        name="password"
        type="password"
        id="password"
        fullWidth
        value={values.password}
        onChange={handleChange}
        onBlur={handleBlur}
        error={!!errors.password}
        helperText={errors.password && touched.password && errors.password}
        margin="normal"
        variant="outlined"
        data-testid="field-password"
      />

      {isSubmitting && (
        <div id="submitting">
          <FormattedMessage id="Submitting" />
        </div>
      )}
      <Button
        type="submit"
        id="submit-button"
        disabled={isSubmitting}
        color="primary"
        variant="contained"
        data-testid="submit-button"
      >
        <FormattedMessage id="Confirm" />
      </Button>
    </Form>
  );
}
Example #25
Source File: register.form.component.tsx    From MyWay-client with MIT License 5 votes vote down vote up
export default function RegisterForm() {
  const router = useRouter();
  const { userStore } = useStores();

  return (
    <Formik
      initialValues={{
        name: "",
        email: "",
        password: "",
      }}
      onSubmit={async (values, { setSubmitting, setStatus }) => {
        userStore
          .register(values)
          .then(() => {
            setStatus({
              message: "ההרשמה עברה בהצלחה. מבצע התחברות ...",
            });
            setTimeout(() => router.push("/"), 2000);
          })
          .catch((e: APIErrorResponse) => {
            setStatus({ error: e.message });
          })
          .finally(() => setSubmitting(false));
      }}
      validationSchema={RegisterSchema}
    >
      {({ isSubmitting, status }) => (
        <Form className="flex w-96 justify-center items-center flex-wrap">
          <FormField name="name" type="text" placeholder="ישראל ישראלי" />
          <ErrorMessage name="name" />

          <FormField name="email" type="email" placeholder="כתובת דוא״ל" />
          <ErrorMessage name="email" />

          <FormField name="password" type="password" placeholder="סיסמה" />
          <ErrorMessage name="password" />

          <StatusMessage formStatus={status} />

          <SubmitButton isSubmitting={isSubmitting} value="התרשמה" />
        </Form>
      )}
    </Formik>
  );
}
Example #26
Source File: PopupFormField.tsx    From firecms with MIT License 4 votes vote down vote up
export function PopupFormField<M extends { [Key: string]: any }>({
                                                                     tableKey,
                                                                     entity,
                                                                     customFieldValidator,
                                                                     name,
                                                                     schemaResolver,
                                                                     path,
                                                                     cellRect,
                                                                     setPreventOutsideClick,
                                                                     open,
                                                                     onClose,
                                                                     columnIndex,
                                                                     onCellValueChange
                                                                 }: PopupFormFieldProps<M>) {

    const [savingError, setSavingError] = React.useState<any>();
    const [popupLocation, setPopupLocation] = useState<{ x: number, y: number }>();
    const [internalValue, setInternalValue] = useState<EntityValues<M> | undefined>(entity?.values);

    const classes = useStyles();
    const windowSize = useWindowSize();

    const ref = React.useRef<HTMLDivElement>(null);
    const containerRef = React.useRef<HTMLDivElement>(null);
    const initialPositionSet = React.useRef<boolean>(false);

    const draggableBoundingRect = ref.current?.getBoundingClientRect();

    useDraggable({
        containerRef,
        ref,
        x: popupLocation?.x,
        y: popupLocation?.y,
        onMove: (x, y) => onMove({ x, y })
    });

    useEffect(
        () => {
            initialPositionSet.current = false;
        },
        [name, entity]
    );

    const getInitialLocation = useCallback(() => {
        if (!cellRect) throw Error("getInitialLocation error");

        return {
            x: cellRect.left < windowSize.width - cellRect.right
                ? cellRect.x + cellRect.width / 2
                : cellRect.x - cellRect.width / 2,
            y: cellRect.top < windowSize.height - cellRect.bottom
                ? cellRect.y + cellRect.height / 2
                : cellRect.y - cellRect.height / 2
        };
    }, [cellRect, windowSize.height, windowSize.width]);

    const normalizePosition = useCallback(({
                                               x,
                                               y
                                           }: { x: number, y: number }) => {
        if (!draggableBoundingRect)
            throw Error("normalizePosition called before draggableBoundingRect is set");

        return {
            x: Math.max(0, Math.min(x, windowSize.width - draggableBoundingRect.width)),
            y: Math.max(0, Math.min(y, windowSize.height - draggableBoundingRect.height))
        };
    }, [draggableBoundingRect, windowSize]);

    const updatePopupLocation = useCallback((position?: { x: number, y: number }) => {
        if (!cellRect || !draggableBoundingRect) return;
        const newPosition = normalizePosition(position ?? getInitialLocation());
        if (!popupLocation || newPosition.x !== popupLocation.x || newPosition.y !== popupLocation.y)
            setPopupLocation(newPosition);
    }, [cellRect, draggableBoundingRect, getInitialLocation, normalizePosition, popupLocation]);

    useEffect(
        () => {
            if (!cellRect || !draggableBoundingRect || initialPositionSet.current) return;
            initialPositionSet.current = true;
            updatePopupLocation(getInitialLocation());
        },
        [cellRect, draggableBoundingRect, getInitialLocation, updatePopupLocation]
    );

    useLayoutEffect(
        () => {
            updatePopupLocation(popupLocation);
        },
        [windowSize, cellRect]
    );

    useEffect(
        () => {
            setPreventOutsideClick(open);
        },
        [open]
    );

    const validationSchema = useMemo(() => {
        if (!schemaResolver) return;
        const schema = computeSchema({
            schemaOrResolver: schemaResolver,
            path,
            values: internalValue,
            previousValues: entity?.values
        });
        return getYupEntitySchema(
            name && schema.properties[name]
                ? { [name]: schema.properties[name] } as Properties<any>
                : {} as Properties<any>,
            customFieldValidator);
    }, [path, internalValue, name]);

    const adaptResize = () => {
        if (!draggableBoundingRect) return;
        return updatePopupLocation(popupLocation);
    };

    const onMove = (position: { x: number, y: number }) => {
        if (!draggableBoundingRect) return;
        return updatePopupLocation(position);
    };

    const saveValue = async (values: M) => {
        setSavingError(null);
        if (entity && onCellValueChange && name) {
            return onCellValueChange({
                value: values[name as string],
                name: name as string,
                entity,
                setError: setSavingError,
                setSaved: () => {
                }
            });
        }
        return Promise.resolve();
    };

    if (!entity)
        return <></>;

    const form = entity && (
        <div
            key={`popup_form_${tableKey}_${entity.id}_${columnIndex}`}
            style={{
                width: 520,
                maxWidth: "100vw",
                maxHeight: "85vh"
            }}>
            <Formik
                initialValues={entity.values}
                validationSchema={validationSchema}
                validate={(values) => console.debug("Validating", values)}
                onSubmit={(values, actions) => {
                    saveValue(values)
                        .then(() => onClose())
                        .finally(() => actions.setSubmitting(false));
                }}
            >
                {({
                      handleChange,
                      values,
                      errors,
                      touched,
                      dirty,
                      setFieldValue,
                      setFieldTouched,
                      handleSubmit,
                      isSubmitting
                  }: FormikProps<EntityValues<M>>) => {

                    if (!isEqual(values, internalValue)) {
                        setInternalValue(values);
                    }

                    if (!entity)
                        return <ErrorView
                            error={"PopupFormField misconfiguration"}/>;

                    if (!schemaResolver)
                        return <></>;

                    const disabled = isSubmitting;

                    const schema = computeSchema({
                        schemaOrResolver: schemaResolver,
                        path,
                        values,
                        previousValues: entity?.values
                    });

                    const context: FormContext<M> = {
                        schema,
                        entityId: entity.id,
                        values
                    };

                    const property: Property<any> | undefined = schema.properties[name];

                    return <Form
                        className={classes.form}
                        onSubmit={handleSubmit}
                        noValidate>

                        {name && property && buildPropertyField<any, M>({
                            name: name as string,
                            disabled: isSubmitting || isReadOnly(property) || !!property.disabled,
                            property,
                            includeDescription: false,
                            underlyingValueHasChanged: false,
                            context,
                            tableMode: true,
                            partOfArray: false,
                            autoFocus: open,
                            shouldAlwaysRerender: true
                        })}

                        <Button
                            className={classes.button}
                            variant="contained"
                            color="primary"
                            type="submit"
                            disabled={disabled}
                        >
                            Save
                        </Button>

                    </Form>;
                }}
            </Formik>

            {savingError &&
            <Typography color={"error"}>
                {savingError.message}
            </Typography>
            }

        </div>
    );

    const draggable = (
        <div
            key={`draggable_${String(name)}_${entity.id}`}
            className={clsx(classes.popup,
                { [classes.hidden]: !open }
            )}
            ref={containerRef}>

            <ElementResizeListener onResize={adaptResize}/>

            <div className={classes.popupInner}
                 ref={ref}>

                {form}

                <IconButton
                    size={"small"}
                    style={{
                        position: "absolute",
                        top: -14,
                        right: -14,
                        backgroundColor: "#666"
                    }}
                    onClick={(event) => {
                        event.stopPropagation();
                        onClose();
                    }}>
                    <ClearIcon style={{ color: "white" }}
                               fontSize={"small"}/>
                </IconButton>
            </div>

        </div>
    );

    return (
        <Portal container={document.body}>
            {draggable}
        </Portal>
    );

}
Example #27
Source File: LogContactForm.tsx    From Frontend with MIT License 4 votes vote down vote up
InnerForm: React.FC<InjectedFormikProps<
  LogContactFormProps,
  FormValues
>> = (props) => {
  const {
    contactOptions,
    dirty,
    errors,
    isSubmitting,
    isValid,
    setFieldValue,
    touched
  } = props;

  const contactWithOptions: ContactWith[] = contactOptions.map(
    (contactUid: string) => {
      const { person } = withPerson({
        uid: contactUid
      });

      return {
        uid: contactUid,
        displayName: person ? person.displayName : ''
      };
    }
  );

  return (
    <Form>
      <Stack spacing={6}>
        <Box>
          <Field name="entryDate">
            {({ field }) => (
              <FormControl
                isInvalid={errors[field.name] && touched[field.name]}
              >
                <FormLabel htmlFor={field.name}>
                  <FormattedMessage id="LogForm.Entry Date" />
                </FormLabel>
                <Box>
                  <DatePicker
                    minDate={new Date('2019-11-01')}
                    calendarIcon={<MdToday />}
                    clearIcon={null}
                    onChange={(v) => setFieldValue('entryDate', v)}
                    value={field.value}
                  />
                </Box>
                <FormErrorMessage>
                  {errors.entryDate}
                </FormErrorMessage>
              </FormControl>
            )}
          </Field>
        </Box>

        <Box>
          <Field name="contactWith">
            {({ field }) => (
              <FormControl
                isInvalid={errors[field.name] && touched[field.name]}
              >
                <FormLabel htmlFor={field.name}>
                  <FormattedMessage id="LogForm.Who did you meet?" />
                </FormLabel>
                <Select
                  getOptionLabel={(o: ContactWith) => o.displayName}
                  getOptionValue={(o: ContactWith) => o.uid}
                  defaultValue={field.value}
                  isMulti
                  name={field.name}
                  options={contactWithOptions}
                  onChange={(option: Option) => {
                    setFieldValue(field.name, option);
                  }}
                />
                <FormHelperText>
                  <FormattedMessage
                    id="LogForm.cant-find"
                    values={{
                      // eslint-disable-next-line react/display-name
                      a: (...chunks) => (
                        <Link
                          color="brand.orange"
                          to="/me/share/"
                          as={IntlLink}
                        >
                          {chunks}
                        </Link>
                      )
                    }}
                  />
                </FormHelperText>
                <FormErrorMessage>
                  {errors.entryDate}
                </FormErrorMessage>
              </FormControl>
            )}
          </Field>
        </Box>
        <Box>
          <Button
            mt={4}
            isDisabled={!(isValid && dirty)}
            variantColor="teal"
            isLoading={isSubmitting}
            type="submit"
          >
            <FormattedMessage id="LogForm.Save" />
          </Button>
        </Box>
      </Stack>
    </Form>
  );
}
Example #28
Source File: BankAccountForm.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 4 votes vote down vote up
BankAccountForm: React.FC<BankAccountFormProps> = ({
  userId,
  createBankAccount,
  onboarding,
}) => {
  const history = useHistory();
  const classes = useStyles();
  const initialValues: BankAccountPayload = {
    userId,
    bankName: "",
    accountNumber: "",
    routingNumber: "",
  };

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={(values, { setSubmitting }) => {
        setSubmitting(true);

        createBankAccount({ ...values, userId });

        if (!onboarding) {
          history.push("/bankaccounts");
        }
      }}
    >
      {({ isValid, isSubmitting }) => (
        <Form className={classes.form} data-test="bankaccount-form">
          <Field name="bankName">
            {({ field, meta: { error, value, initialValue, touched } }: FieldProps) => (
              <TextField
                variant="outlined"
                margin="dense"
                fullWidth
                required
                id={"bankaccount-bankName-input"}
                type="text"
                placeholder="Bank Name"
                data-test={"bankaccount-bankName-input"}
                error={(touched || value !== initialValue) && Boolean(error)}
                helperText={touched || value !== initialValue ? error : ""}
                {...field}
              />
            )}
          </Field>
          <Field name="routingNumber">
            {({ field, meta: { error, value, initialValue, touched } }: FieldProps) => (
              <TextField
                variant="outlined"
                margin="dense"
                fullWidth
                required
                id={"bankaccount-routingNumber-input"}
                type="text"
                placeholder="Routing Number"
                data-test={"bankaccount-routingNumber-input"}
                error={(touched || value !== initialValue) && Boolean(error)}
                helperText={touched || value !== initialValue ? error : ""}
                {...field}
              />
            )}
          </Field>
          <Field name="accountNumber">
            {({ field, meta: { error, value, initialValue, touched } }: FieldProps) => (
              <TextField
                variant="outlined"
                margin="dense"
                fullWidth
                required
                id={"bankaccount-accountNumber-input"}
                type="text"
                placeholder="Account Number"
                data-test={"bankaccount-accountNumber-input"}
                error={(touched || value !== initialValue) && Boolean(error)}
                helperText={touched || value !== initialValue ? error : ""}
                {...field}
              />
            )}
          </Field>
          <Grid container spacing={2} direction="row" justify="flex-start" alignItems="flex-start">
            <Grid item>
              <Button
                type="submit"
                fullWidth
                variant="contained"
                color="primary"
                className={classes.submit}
                data-test="bankaccount-submit"
                disabled={!isValid || isSubmitting}
              >
                Save
              </Button>
            </Grid>
          </Grid>
        </Form>
      )}
    </Formik>
  );
}
Example #29
Source File: ProposalForm.tsx    From panvala with Apache License 2.0 4 votes vote down vote up
ProposalForm: React.SFC<IProps> = ({ onHandleSubmit }) => {
  return (
    <div>
      <Formik
        initialValues={
          process.env.NODE_ENV === 'development'
            ? dummyValues
            : {
                firstName: '',
                lastName: '',
                email: '',
                github: '',
                tokensRequested: '',
                title: '',
                summary: '',
                website: '',
                projectPlan: '',
                projectTimeline: '',
                teamBackgrounds: '',
                file: {},
                totalBudget: '',
                otherFunding: '',
                awardAddress: '',
              }
        }
        validationSchema={GrantProposalFormSchema}
        onSubmit={async (values, { setSubmitting, setFieldError }) => {
          try {
            // throws on underflow (x.1234567890123456789)
            const tokensRequested = convertedToBaseUnits(values.tokensRequested, 18);

            const baseUnitsValues = {
              ...values,
              tokensRequested,
              // max: totalUpcomingDispatch
            };
            await onHandleSubmit(baseUnitsValues);
          } catch (error) {
            setFieldError('tokensRequested', 'Number cannot have more than 18 decimals');
          }

          setSubmitting(false);
        }}
      >
        {({ isSubmitting, setFieldValue, handleSubmit }) => (
          <Box>
            <Form>
              <PaddedDiv>
                <SectionLabel>{'PERSONAL INFORMATION'}</SectionLabel>

                <FieldText
                  required
                  label={'First Name / Organization'}
                  name="firstName"
                  placeholder="Enter your first name or the name of your organization"
                />
                <FieldText label={'Last Name'} name="lastName" placeholder="Enter your last name" />
                <FieldText required label={'Email'} name="email" placeholder="Enter your email" />
                <FieldText
                  label={'Github'}
                  name="github"
                  placeholder="Enter your github username"
                />
              </PaddedDiv>

              <Separator />

              <PaddedDiv>
                <SectionLabel>{'PROJECT DETAILS'}</SectionLabel>

                <FieldText
                  required
                  label={'Project Name'}
                  name="title"
                  placeholder="Enter project name"
                />
                <FieldText label={'Website'} name="website" placeholder="Enter project website" />

                <FieldTextarea
                  required
                  label={'Project Summary'}
                  name="summary"
                  placeholder="Enter project proposal"
                />
                <FieldTextarea
                  label={'Timeline and Milestones'}
                  name="projectTimeline"
                  placeholder="Enter project timeline and milestones"
                />
                <FieldTextarea
                  label={"What are your and your team's backgrounds?"}
                  name="teamBackgrounds"
                  placeholder="Enter your and your team's backgrounds"
                />

                <Label htmlFor="file">{'File upload'}</Label>
                <Box mt={2}>
                  <input
                    type="file"
                    name="file"
                    onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                      if (!event.currentTarget.files) {
                        return;
                      }
                      const file = event.currentTarget.files[0];
                      if (file.type !== 'application/pdf') {
                        toast.error('Invalid file type. Please upload .pdf');
                        setFieldValue('file', {});
                      } else {
                        setFieldValue('file', file);
                      }
                    }}
                    placeholder="Choose file"
                  />
                </Box>
              </PaddedDiv>

              <Separator />

              <PaddedDiv>
                <SectionLabel>{'FINANCIAL DETAILS'}</SectionLabel>

                <FieldTextarea
                  label={'What is the total budget of your project (in USD)?'}
                  name="totalBudget"
                  placeholder="Enter the total budget of your project"
                />

                <FieldText
                  required
                  label={'How many tokens are you requesting?'}
                  name="tokensRequested"
                  placeholder="Enter the amount of tokens you would like"
                />

                <FieldText
                  required
                  label={'Ethereum wallet address for award'}
                  name="awardAddress"
                  placeholder="Enter the address of the token recipient for this proposal"
                />

                <FieldTextarea
                  label={'Have you applied/received other funding?'}
                  name="otherFunding"
                  placeholder="Enter any other funding you have received"
                />
              </PaddedDiv>

              <Separator />
            </Form>

            <Flex p={4} justifyEnd>
              <BackButton />
              <Button type="submit" large primary disabled={isSubmitting} onClick={handleSubmit}>
                {'Confirm and Submit'}
              </Button>
            </Flex>
          </Box>
        )}
      </Formik>
    </div>
  );
}