formik#Form JavaScript 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: SearchInput.js    From carpal-fe with MIT License 6 votes vote down vote up
function SearchInput(props) {
    return (
        <div data-testid="input-field" className="search-ride-input">
            <Form>
                <Field
                    className="formik-search-fields"
                    type="text"
                    name="pickup"
                    placeholder="Pick up..."
                />
                <Field
                    className="formik-search-fields"
                    type="text"
                    name="dropof"
                    placeholder="Destination..."
                />
            </Form>
        </div>
    );
}
Example #2
Source File: Module2.test.js    From foster-together-fe with MIT License 6 votes vote down vote up
test("Best Practices is rendered", async () => {
  render(
    <Formik initialValues={initialValues}>
      {props => (
        <Form>
          <Module22 {...props} />
        </Form>
      )}
    </Formik>
  );
});
Example #3
Source File: FormPageTwo.test.js    From neighborhood-chef-fe with MIT License 6 votes vote down vote up
describe("Test FormPageTwo component", () => {
  let FormPageTwoComponent;
  let store;

  beforeEach(() => {
    store = mockStore({});
    FormPageTwoComponent = render(
      <Provider store={store}>
        <BrowserRouter>
          <Formik>
            <Form>
              <FormPageTwo
                handleChange={handleChange}
                hashtags={[{ id: 1, title: "#hashtags" }]}
                allergenList={[]}
                dietWarnings={[]}
                ingredientList={[]}
              />
            </Form>
          </Formik>
        </BrowserRouter>
      </Provider>
    );
  });

  test("FormPageTwo component renders", () => {
    expect(FormPageTwoComponent).toBeDefined();
    expect(FormPageTwoComponent.getByText(/#hashtags/i));
  });
});
Example #4
Source File: Input.stories.js    From jasper with MIT License 6 votes vote down vote up
TestFormik = ({ children }) => (
  <Formik
    initialValues={{}}
    onSubmit={(values, actions) => {
      window.alert(JSON.stringify(values, null, 2))
      actions.setSubmitting(false)
    }}
  >
    {({ errors }) => (
      <Form>
        {children}
        {Object.keys(errors).map((key) => (
          <span key={key}>
            {key}: {errors[key]}
          </span>
        ))}
        <button type="submit">Submit</button>
      </Form>
    )}
  </Formik>
)
Example #5
Source File: AppTasks.js    From course-manager with MIT License 6 votes vote down vote up
export default function AppTasks() {
  const formik = useFormik({
    initialValues: {
      checked: [TASKS[2]]
    },
    onSubmit: (values) => {
      console.log(values);
    }
  });

  const { values, handleSubmit } = formik;

  return (
    <Card>
      <CardHeader title="Tasks" />
      <Box sx={{ px: 3, py: 1 }}>
        <FormikProvider value={formik}>
          <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
            {TASKS.map((task) => (
              <TaskItem
                key={task}
                task={task}
                formik={formik}
                checked={values.checked.includes(task)}
              />
            ))}
          </Form>
        </FormikProvider>
      </Box>
    </Card>
  );
}
Example #6
Source File: ComplexFormBuilder.jsx    From dineforward with MIT License 6 votes vote down vote up
ComplexFormBuilder = props => {
  const { children, formAction, values, schema } = props;
  let { incomingValues } = props;
  const [form, setForm] = React.useState(schema);
  const [formFields, setFormFields] = React.useState(form);
  const [vals, setVals] = React.useState(incomingValues);

  if (!incomingValues || incomingValues === null) {
    incomingValues = Object.assign({}, ...schema.fields.map(m => ({ [m.name]: '' })));
  }

  return (
    <Formik initialValues={incomingValues} onSubmit={formAction} enableReinitialize>
      {formikProps => (
        <Form>
          <FormElements form={form} />
          {children ? children(formikProps) : DefaultButtons(formikProps)}
        </Form>
      )}
    </Formik>
  );
}
Example #7
Source File: DatesField.test.js    From react-invenio-deposit with MIT License 6 votes vote down vote up
it('renders without crashing', () => {
  const div = document.createElement('div');
  const options = {
    type: [
      {
        text: 'type Text 1',
        value: 'typeValue1',
      },
      {
        text: 'type Text 2',
        value: 'typeValue2',
      },
    ],
  };

  ReactDOM.render(
    <Formik>
      {(props) => (
        <Form>
          <DatesField fieldPath={'fieldPath'} options={options} />
        </Form>
      )}
    </Formik>,
    div
  );
});
Example #8
Source File: RadioField.test.js    From react-invenio-forms with MIT License 6 votes vote down vote up
it("renders without crashing", () => {
  const div = document.createElement("div");
  ReactDOM.render(
    <Formik>
      {() => (
        <Form>
          <RadioField
            checked
            fieldPath="testFieldPath"
            label="testLabel"
            labelIcon="money"
            optimized={false}
            onChange={() => null}
            value="testValue"
          />
        </Form>
      )}
    </Formik>,
    div
  );
});
Example #9
Source File: FormFormik.js    From AED-Map with MIT License 6 votes vote down vote up
FormFormik = ({ onSubmit }) => {
  const classes = useStyles();

  return (
    <Form
      className={classes.form}
      autoComplete="off"
      onSubmit={onSubmit}
    >
      <MyTextField
        label="Назва"
        name="title"
        className={classes.inputs}
      />
      <MySelect
        labelTitle="Мова інтерфейсу"
        label="language"
        name="language"
        options={languageInterface}
        classes={classes.inputs}
      />
      <MySelect
        labelTitle="Інформаційні таблички"
        label="informational_plates"
        name="informational_plates"
        options={informationalPlates}
        classes={classes.inputs}
      />
      <MySelect
        labelTitle="Години роботи"
        label="accessibility"
        name="accessibility"
        options={accessibility}
        classes={classes.inputs}
      />
      <FormButtons />
    </Form>
  );
}
Example #10
Source File: ForgotForm.jsx    From awesome-react-starter with MIT License 6 votes vote down vote up
ForgotForm = () => {
  const ref = useRef(null);
  const handleSubmit = async (values) => {
    await forgot(ref, values);
  };

  return (
    <Formik
      validationSchema={validationSchema}
      initialValues={initialValues}
      onSubmit={handleSubmit}
    >
      <Form className="space-y-4">
        <Fieldset name="email" label="Your email">
          <Field id="email" name="email" as={Email} autoFocus />
        </Fieldset>
        <Submit className="button full primary">Send password reset email</Submit>
        <Recaptcha ref={ref} />
      </Form>
    </Formik>
  );
}
Example #11
Source File: LogIn.js    From Next.js-e-commerce-online-store with MIT License 5 votes vote down vote up
export default function LogIn({ showResetPassword }) {
  return (
    <DivLogIn className="border-left border-bottom border-right">
      <Formik
        initialValues={{
          email: '',
          password: '',
          isChecked: false
        }}
        validate={values => {
          const errors = {}
          if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
            errors.email = 'Invalid email address'
          }
          return errors
        }}
        onSubmit={(data, { setSubmitting }) => {
          setSubmitting(true)
          alert(`Your email is: ${data.email}, \nyour password is: ${data.password}, \nyou ${data.isChecked ? 'checked' : 'didn\'t check'} checkbox.`)
          setSubmitting(false)
        }}
      >
        {({ errors, isSubmitting }) => (
          <Form name="LogIn">
            <label>
              Email:
              <Field type="email" name="email" required />
              {errors.email ? <div>{errors.email}</div> : null} 
            </label>
            <label>
              Password:
              <Field type="password" name="password" minlength="6" required />
            </label>
            <div className="form-check">
              <label className="form-check-label" htmlFor="autoSizingCheck">
                <Field 
                  type="checkbox" 
                  name="isChecked" 
                  className="form-check-input" 
                  id="autoSizingCheck"
                />
                Remember Me
              </label>
            </div>
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </Form>
        )}        
      </Formik>
      <div className="dropdown-divider"></div>
      <a className="dropdown-item badge badge-light" href="/#" onClick={showResetPassword}>
        Reset Password
      </a>
    </DivLogIn>
  )
}
Example #12
Source File: Login.js    From carpal-fe with MIT License 5 votes vote down vote up
function Login(props) {
    const { errors, touched } = props;
    useEffect(() => {
        let token = document.cookie.replace(
            /(?:(?:^|.*;\s*)auth\s*\s*([^;]*).*$)|^.*$/,
            "$1"
        );
        if (token) {
            localStorage.setItem("token", token);
            //destroy auth cookie
            document.cookie =
                "auth=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
            //push user to profile page
            props.history.push("/profilepage");
        }
    }, [localStorage.getItem("token")]);
    return (
        <div className="login-container">
            {/* form container */}
            <Form className="formik-container">
                <p role="login-component" className="login-p">
                    Login
                </p>
                <LabelField
                    name="email"
                    touched={touched.email}
                    error={errors.email}
                    type="email"
                    placeholder="[email protected]"
                />

                <LabelField
                    name="password"
                    type="password"
                    touched={touched.password}
                    error={errors.password}
                    placeholder="Password"
                />

                {!props.error ? null : (
                    <p className="form-error">
                        {props.error.response.data.message}
                    </p>
                )}

                <button type="submit">Submit</button>
                {/* <a className="btn" href={getGoogleRoute()}>
                    Login With Google
                </a> */}
                <Link className="forgot-password" to="/signup">
                    Forgot your password?
                </Link>
            </Form>

            <div className="module-nav">
                <img className="module-cuties" src={cuties} alt="cuties" />

                <p className="module-p">
                    New to the website?
                    <Link className="signup-link" to="/signup">
                        Sign Up!
                    </Link>
                </p>
            </div>
        </div>
    );
}
Example #13
Source File: index.js    From foster-together-fe with MIT License 5 votes vote down vote up
InputContainer = styled(Form)`
  width: 75%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin: auto 0;
`
Example #14
Source File: FormPageThree.test.js    From neighborhood-chef-fe with MIT License 5 votes vote down vote up
describe("Test FormPageThree component", () => {
  let FormPageThreeComponent;
  let store;
  beforeEach(() => {
    store = mockStore({});
    FormPageThreeComponent = render(
      <Provider store={store}>
        <Formik>
          <Form>
            <FormPageThree
              values={values}
              handleChange={handleChange}
              modifiers={[
                {
                  id: 1,
                  title: "18+",
                  icon: "bottle icon",
                  active: false,
                },
              ]}
              hashtags={[{ id: 1, title: "#hashtag" }]}
              dietWarnings={[]}
              allergenList={[]}
              ingredientList={[]}
            />
          </Form>
        </Formik>
      </Provider>
    );
  });

  test("FormPageThree component renders", () => {
    expect(FormPageThreeComponent).toBeDefined();
    expect(
      FormPageThreeComponent.getByText(
        /Double check if your event details are correct/i
      )
    );
  });
});
Example #15
Source File: profile.js    From supportal-frontend with MIT License 5 votes vote down vote up
UserProfileForm = () => {
  const { profile, updateProfile } = useContext(AuthContext);
  const [error, setError] = useState(null);
  const formData = profile || {};
  const router = useRouter();
  useErrorMessage(!!error, error);

  const handleSubmit = async (values, actions) => {
    setError(null);
    actions.setStatus(null);
    actions.setSubmitting(true);
    try {
      await updateProfile(values);
      router.push('/');
    } catch (err) {
      if (err.response) {
        // There was a validation error. Show field-level errors.
        actions.setStatus(err.response.data);
      } else {
        // Something else funky happened. Show a top-level error notification.
        setError(err.message);
      }
      actions.setSubmitting(false);
    }
  };

  const fields = [
    { label: 'First Name', name: 'first_name' },
    { label: 'Last Name', name: 'last_name' },
    { label: 'Phone Number', type: 'tel', name: 'phone' },
    { label: 'Address', name: 'address' },
    { label: 'City', name: 'city' },
    { label: 'State', name: 'state' },
    { label: 'Zip Code', name: 'zip5', maxLength: '5', pattern: '[0-9]{5}' },
    {
      label: 'Team Name (not required)',
      name: 'self_reported_team_name',
      required: false,
    },
  ];
  return (
    <Formik
      initialValues={{
        ...formData,
        phone: getFormattedPhone(formData.phone, true),
      }}
      onSubmit={handleSubmit}
    >
      {({ isSubmitting, status }) => (
        <Form data-tracking="form-user-profile">
          {fields.map(item => (
            <FormikField
              className="mb-8"
              theme={Themes.INVERTED}
              key={item.name}
              error={status && status[item.name]}
              {...item}
            />
          ))}
          {/* <PushNotificationToggle className="mb-8" /> */}
          <Button
            type="submit"
            disabled={isSubmitting}
            className="hover:text-white"
          >
            Update Details
          </Button>
        </Form>
      )}
    </Formik>
  );
}
Example #16
Source File: Feedback.js    From Simplify-Testing-with-React-Testing-Library with MIT License 5 votes vote down vote up
Feedback = props => (
  <main className="flex flex-col w-2/3 m-auto py-2">
    <h1 className="text-2xl text-gray-900 font-semibold m-auto">
      We'd love to hear your thoughts!
    </h1>

    <Formik
      initialValues={{ name: '', email: '', rating: '', comments: '' }}
      validate={formValidator}
      onSubmit={values => props.onSubmit(values)}
    >
      {({ isSubmitting }) => (
        <Form className="form bg-white p-6 my-10 relative">
          <p className="text-red-600 mb-1">
            All fields marked with * are required
          </p>

          <label>
            Name *
            <Field
              type="text"
              name="name"
              placeholder="Name here"
              className="border p-2 w-full mt-3"
            />
          </label>
          <ErrorMessage name="name" component="div" className="text-red-600" />
          <label>
            Email *
            <Field
              type="email"
              name="email"
              placeholder="Email here"
              className="border p-2 w-full mt-3"
            />
          </label>

          <ErrorMessage name="email" component="div" className="text-red-600" />
          <label>
            Rating *
            <Field as="select" name="rating" className="border p-2 w-full mt-3">
              <option value=""></option>
              <option value="Awesome">Awesome</option>
              <option value="Good">Good</option>
              <option value="Bad">Bad</option>
            </Field>
          </label>
          <ErrorMessage
            name="rating"
            component="div"
            className="text-red-600"
          />

          <label>
            Comments *
            <Field
              as="textarea"
              name="comments"
              placeholder="comments here"
              className="border p-2 w-full mt-3"
            />
          </label>
          <ErrorMessage
            name="comments"
            component="div"
            className="text-red-600"
          />
          <button
            type="submit"
            disabled={isSubmitting}
            className="w-full mt-6 bg-blue-600 hover:bg-blue-500 text-white font-semibold p-3"
          >
            Submit
          </button>
        </Form>
      )}
    </Formik>
  </main>
)
Example #17
Source File: FormikStepper.js    From dscbppimt-official-website with MIT License 5 votes vote down vote up
export function FormikStepper({ children, ...props}) {
    console.log(props.renderFormikForm)
    const [step, setStep] = useState(0);
    const [completed, setCompleted] = useState(false);
  
    function isLastStep() {
      return step === props.labels.length - 2;
    }
    return (
      <Formik
        {...props}
        validationSchema={props.validationSchemas[step]}
        onSubmit={async (values, helpers) => {
          if (isLastStep()) {
            helpers.setSubmitting(true);
            try{
              await props.onSubmit(values, helpers);
            }catch(e){
              console.log(e)
            }
            helpers.setSubmitting(false);
            setStep((s) => s + 1);
            setCompleted(true);
          } else {
            setStep((s) => s + 1);
          }
        }}
      >
        {({ values, isSubmitting, errors, touched, status }) => (
          <Form autoComplete="off" noValidate>
            { isSubmitting && <LinearProgress />}
            <Stepper alternativeLabel activeStep={step}>
              {props.labels.map((index) => (
                <Step key={index} completed={step > index || completed}>
                  <StepLabel>{index}</StepLabel>
                </Step>
              ))}
            </Stepper>
  
            { props.renderFormikForm(step, values, errors, touched, status) }
            { step <= props.labels.length - 2 &&
              <Grid container spacing={2} justifyContent="flex-end" style={{marginTop : '2em'}}>
              {step > 0 ? (
                <Grid item>
                  <Button
                    style={{width : '110px'}}
                    disabled={isSubmitting}
                    variant="contained"
                    color="primary"
                    onClick={() => setStep((s) => s - 1)}
                  >
                    Back
                  </Button>
                </Grid>
              ) : null}
              <Grid item>
                <Button
                  style={{width : '110px'}}
                  disabled={isSubmitting}
                  variant="contained"
                  color="primary"
                  type="submit"
                >
                  {isSubmitting ? 'Submitting' : step === props.labels.length - 2 ? 'Submit' : 'Next'}
                </Button>
              </Grid>
            </Grid>
            }

          </Form>
        )}
      </Formik>
    );
  }
Example #18
Source File: CompanyStaffUpdate.jsx    From hrms-project-frontend with MIT License 5 votes vote down vote up
export default function CompanyStaffUpdate() {
  const [companyStaff, setCompanyStaff] = useState(null);

  const companyStaffService = useMemo(() => new CompanyStaffService(), []),
    getById = useCallback(async () => {
      const user = { id: 3 }, //TODO Login Redux
        result = await companyStaffService.getById(user.id);
      if (result.data.success) setCompanyStaff(result.data.data);
    }, [companyStaffService]),
    updateByUser = async (values) => {
      const updatedCompanyStaff = {
          id: companyStaff.id,
          ...values,
        },
        result = await companyStaffService.updateByUser(updatedCompanyStaff);

      if (result.data.success) {
        toast.success(result.data.message);
        setCompanyStaff(updatedCompanyStaff);
      }
    };

  useEffect(() => {
    getById();
  }, [getById]);

  const initialValues = {
      password: "",
    },
    validationSchema = Yup.object().shape({
      firstName: Yup.string().required(),
      lastName: Yup.string().required(),
      password: Yup.string().required(),
    });

  return (
    <div className='container'>
      <DisplayHeader firstText='Edit' secondText='Employer Information' size='5' />
      {companyStaff ? (
        <Formik
          initialValues={{
            firstName: companyStaff.firstName,
            lastName: companyStaff.lastName,
            ...initialValues,
          }}
          validationSchema={validationSchema}
          onSubmit={(values) => updateByUser(values)}
        >
          <Form>
            <FormInput name='firstName' />
            <FormInput name='lastName' />
            <FormInput type='password' name='password' />
            <button type='submit' className='btn btn-primary w-100 mt-3'>
              Save
            </button>
          </Form>
        </Formik>
      ) : (
        <LoadingSpinner />
      )}
    </div>
  );
}
Example #19
Source File: Form.js    From codeclannigeria-frontend with MIT License 5 votes vote down vote up
SignupForm = () => {
  return (
    <Formik
      initialValues={{ firstName: '', lastName: '', email: '', password: '' }}
      validationSchema={Yup.object({
        firstName: Yup.string()
          .max(15, 'Must be 15 characters or less')
          .required('Required'),
        lastName: Yup.string()
          .max(20, 'Must be 20 characters or less')
          .required('Required'),
        email: Yup.string().email('Invalid email address').required('Required'),
        password: Yup.string().required('Required'),
      })}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      <SignupStyled>
        <div id="wrapper">
          <div id="signUpInfo">
            <img
              src="./img/codeclannglogo.png"
              alt="Code Clan Logo"
              id="logo"
            />
            <h1 class="infoHeading">
              welcome to CodeClan
              <br />
              Nigeria
            </h1>
            <p class="infoSubheading">sign up to</p>
            <img src="./img/keyToComputer.png " alt="" id="infoIllustration" />
          </div>
          <div id="signUpDiv">
            <h1 class="none show">register</h1>
            <h2 class="none display">Create a Code Clan account</h2>
            <Form id="signUpForm">
              <AlertComponent variant="danger" />
              <p className="info blue signUp">sign up with email</p>
              <div className="nameInputGroup">
                <label htmlFor="firstName">First Name</label>
                <br />

                <Field name="firstName" id="firstName" type="text" />
                <ErrorMessage name="firstName" />
                <label htmlFor="lastName">Last Name</label>
                <Field name="lastName" type="text" />
                <ErrorMessage name="lastName" />
              </div>
              <label htmlFor="email">Email Address</label>
              <Field name="email" type="email" />
              <ErrorMessage name="email" />
              <p className="info blue privacy">
                by clicking on this button, you agree to our Terms of use and
                privacy policy
              </p>
              <button disabled className="submit">
                Sign up
              </button>
              <p className="info blue signIn">
                already have an account?
                <span>
                  <Link to="/login/">Sign In</Link>
                </span>
              </p>
            </Form>
          </div>
        </div>
      </SignupStyled>
    </Formik>
  );
}
Example #20
Source File: ForgotPassword.jsx    From react-signup-verification-boilerplate with MIT License 5 votes vote down vote up
function ForgotPassword() {
    const initialValues = {
        email: ''
    };

    const validationSchema = Yup.object().shape({
        email: Yup.string()
            .email('Email is invalid')
            .required('Email is required')
    });

    function onSubmit({ email }, { setSubmitting }) {
        alertService.clear();
        accountService.forgotPassword(email)
            .then(() => alertService.success('Please check your email for password reset instructions'))
            .catch(error => alertService.error(error))
            .finally(() => setSubmitting(false));
    }

    return (
        <Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}>
            {({ errors, touched, isSubmitting }) => (
                <Form>
                    <h3 className="card-header">Forgot Password</h3>
                    <div className="card-body">
                        <div className="form-group">
                            <label>Email</label>
                            <Field name="email" type="text" className={'form-control' + (errors.email && touched.email ? ' is-invalid' : '')} />
                            <ErrorMessage name="email" component="div" className="invalid-feedback" />
                        </div>
                        <div className="form-row">
                            <div className="form-group col">
                                <button type="submit" disabled={isSubmitting} className="btn btn-primary">
                                    {isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
                                    Submit
                                </button>
                                <Link to="login" className="btn btn-link">Cancel</Link>
                            </div>
                        </div>
                    </div>
                </Form>
            )}
        </Formik>        
    )
}
Example #21
Source File: ReminderForm.js    From jc-calendar with MIT License 5 votes vote down vote up
render() {
    return (
      <Formik
        initialValues={this.getInitialValues()}
        validationSchema={ReminderSchema}
        onSubmit={this.handleSubmit}
      >
        <Form className="w-full flex flex-col gap-3">
          <FormFieldset>
            <FormLabel htmlFor="description">
              What do you want to remember?
            </FormLabel>
            <div className="flex flex-row flex-wrap gap-2">
              <Field
                id="description"
                name="description"
                component={FormTextInput}
                placeholder="e.g.: Buy milk"
                className="flex-grow"
              />
              <Field
                name="color"
                as={ReminderColorPicker}
                className="flex-shrink"
              />
            </div>
            <ErrorMessage component={FormErrorMessage} name="description" />
            <ErrorMessage component={FormErrorMessage} name="color" />
          </FormFieldset>

          <FormFieldset>
            <FormLabel htmlFor="date">When?</FormLabel>

            <div className="flex flex-row flex-wrap gap-2">
              <Field
                id="date"
                name="date"
                component={FormDatePicker}
                className="flex-grow"
              />
              <Field
                id="time"
                name="time"
                component={FormTimePicker}
                className="w-full sm:w-44"
              />
            </div>
            <ErrorMessage component={FormErrorMessage} name="date" />
            <ErrorMessage component={FormErrorMessage} name="time" />
          </FormFieldset>

          <FormFieldset>
            <FormLabel htmlFor="city">Where?</FormLabel>
            <Field
              id="city"
              name="city"
              component={FormTextInput}
              placeholder="e.g.: New York City"
            />
            <ErrorMessage component={FormErrorMessage} name="city" />
          </FormFieldset>

          <ReminderForecastContainer names={{ city: 'city', date: 'date' }} />

          <FormActions>
            <BaseButton
              type="submit"
              className="bg-indigo-700 hover:bg-indigo-500 text-white"
            >
              <CheckIcon svgClassName="w-6 h-6" />
              Confirm
            </BaseButton>
          </FormActions>
        </Form>
      </Formik>
    );
  }
Example #22
Source File: recovery.js    From horondi_client_fe with MIT License 5 votes vote down vote up
Recovery = () => {
  const styles = useStyles();
  const { t, i18n } = useTranslation();
  const language = i18n.language === 'ua' ? 0 : 1;
  const [shouldValidate, setShouldValidate] = useState(false);

  const { error, userRecovered, recoveryLoading } = useSelector(({ User }) => ({
    recoveryLoading: User.recoveryLoading,
    error: User.error,
    userRecovered: User.userRecovered
  }));

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(userHasRecovered(false));
    dispatch(resetState());
  }, [dispatch]);

  const handleRecovery = async ({ email }) => {
    email && dispatch(recoverUser({ email, language, redirect: true }));
  };

  const successWindow = (
    <div>
      <h2 className={styles.heading}>{t('recovery.successTitle')}</h2>
      <p className={styles.recoveryText}>{t('recovery.successText')}</p>
    </div>
  );

  const validationSchema = Yup.object({
    email: Yup.string().email(t('error.profile.email'))
  });

  return (
    <Formik
      onSubmit={handleRecovery}
      initialValues={{ email: '' }}
      validationSchema={validationSchema}
      validateOnBlur={shouldValidate}
      validateOnChange={shouldValidate}
    >
      {({ errors, handleChange }) => (
        <AuthWrapper>
          {userRecovered || recoveryLoading ? (
            handleRecoveryLoaderOrWindow(userRecovered, successWindow)
          ) : (
            <Form className={styles.background}>
              <AuthHeading>{t('recovery.recoveryTitle')}</AuthHeading>
              <Field
                name='email'
                as={TextField}
                type='text'
                label={t('recovery.recoveryEmail')}
                className={`${styles.emailInput} ${handleClass(errors.email, styles.helperEmail)}`}
                variant='outlined'
                fullWidth
                onChange={(e) => handleChange(e) || (error && dispatch(resetState()))}
                helperText={handleHelperText(errors.email, error)}
                error={!!errors.email || !!error}
                color={MATERIAL_UI_COLOR.PRIMARY}
              />

              <p className={styles.recoveryText}>{t('recovery.recoveryText')}</p>
              <AuthButton onclick={() => setShouldValidate(true)}>
                {t('recovery.recoveryButtonText')}
              </AuthButton>
            </Form>
          )}
        </AuthWrapper>
      )}
    </Formik>
  );
}
Example #23
Source File: doubleDateFilter.js    From what-front with MIT License 5 votes vote down vote up
DoubleDateFilter = (props) => {
  const { rawItemsList, setFilteredItemsList, component } = props;
  let initialStartDate = `${new Date().getFullYear()}-01-01`;
  let initialFinishDate = `${commonHelpers.transformDateTime({}).reverseDate}`;
  let rawList;

  switch(component){
    case 'lessons': {
      rawList = rawItemsList.map(item => {
        const lessonDate = commonHelpers.transformDateTime({dateTime: item.lessonDate}).formInitialValue;
        return item = {...item, 
          startDate: lessonDate, 
          finishDate: lessonDate};
      });
      const d = new Date();
      d.setDate(d.getDate() - 15);
      initialStartDate = `${commonHelpers.transformDateTime({dateTime:d}).reverseDate}`;
      break;
    }
    default: {
      rawList = rawItemsList;
      break;
    }
  }


  const validate = ({ startDate, finishDate }) => startDate > finishDate && {startDate: ' ', finishDate: ' '};

  const filterByDate = ({ startDate, finishDate }) => {
    const newArray = rawList
      .filter((item) => {
        return (new Date(item.startDate.slice(0, 10)) >= new Date(startDate)) 
        && (new Date(item.finishDate.slice(0, 10)) <= new Date(finishDate))
      }
    );

    setFilteredItemsList(newArray);
  };

  return (
    <Formik
      initialValues={{
        startDate: initialStartDate,
        finishDate: initialFinishDate,
      }}
      validate={validate}
      onSubmit={filterByDate}
      >
      {({ errors }) => (
        <Form name="start-group" className="row d-flex">
            <div className="col-5">
              <Field
                className={classNames('form-control', { 'border-danger': errors.startDate })}
                type="date"
                name="startDate"
                id="startDate"
              />
            </div>
            <div className="col-5">
              <Field
                className={classNames('form-control', { 'border-danger': errors.finishDate })}
                type="date"
                name="finishDate"
                id="finishDate"
              />
          </div>
          <div className="col-2 text-right">
            <Button type="submit">
              Filter
            </Button>
          </div>
        </Form>
      )}
    </Formik>
  )
}
Example #24
Source File: ElRewardsVault.js    From lido-dao with GNU General Public License v3.0 5 votes vote down vote up
ElRewardsVault = () => {
  const { api } = useAragonApi()
  const { elRewardsVault } = useAppState()

  const [sidePanelOpen, setSidePanelOpen] = useState(false)
  const openSidePanel = () => setSidePanelOpen(true)
  const closeSidePanel = () => setSidePanelOpen(false)

  const submit = ({ vault }) => {
    api
      .setELRewardsVault(vault)
      .toPromise()
      .catch(console.error)
      .finally(closeSidePanel)
  }

  return (
    <ListItem label="EL Rewards Vault">
      <Controls>
        <LoadableElement value={elRewardsVault}>
          <IdentityBadge entity={elRewardsVault} />
        </LoadableElement>
        <IconButton label="edit" icon={<IconEdit />} onClick={openSidePanel} />
      </Controls>
      <SidePanel
        opened={sidePanelOpen}
        title="Change EL Rewards Vault"
        onClose={closeSidePanel}
      >
        <InfoSpaced title="Action">
          Set a new address for the execution layer rewards vault contract.
        </InfoSpaced>
        <Formik
          initialValues={initialValues}
          validationSchema={validationSchema}
          validateOnBlur={false}
          validateOnChange={false}
          onSubmit={submit}
        >
          {({ submitForm, isSubmitting, isValidating }) => {
            const handleSubmit = (event) => {
              event.preventDefault()
              submitForm()
            }

            return (
              <Form onSubmit={handleSubmit}>
                <Field
                  name={fieldName}
                  type="text"
                  label="Vault"
                  component={TextField}
                />
                <Button
                  mode="strong"
                  wide
                  required
                  disabled={isValidating || isSubmitting}
                  label="Set EL rewards vault"
                  type="submit"
                />
              </Form>
            )
          }}
        </Formik>
      </SidePanel>
    </ListItem>
  )
}
Example #25
Source File: index.js    From realworld with MIT License 5 votes vote down vote up
export function LoginForm({ onSubmit }) {
  return (
    <div className="container page">
      <div className="row">
        <div className="col-md-6 offset-md-3 col-xs-12">
          <h1 className="text-xs-center">Sign in</h1>
          <p className="text-xs-center">
            <Link href="/register">
              <a>Need an account?</a>
            </Link>
          </p>
          <Formik
            validationSchema={validationSchema}
            initialStatus={[]}
            initialValues={{ input: { email: '', password: '' } }}
            onSubmit={onSubmit}
          >
            <Form>
              <ul className="error-messages">
                <ErrorMessage component="li" name="input.email" />
                <ErrorMessage component="li" name="input.password" />
                <FormikStatusErrors />
              </ul>
              <fieldset className="form-group">
                <label>Email</label>
                <Field
                  name="input.email"
                  className="form-control form-control-lg"
                  type="text"
                  placeholder="[email protected]"
                  autoComplete="email"
                />
              </fieldset>
              <fieldset className="form-group">
                <label>Password</label>
                <Field
                  name="input.password"
                  className="form-control form-control-lg"
                  type="password"
                  placeholder="A strong password"
                  autoComplete="current-password"
                />
              </fieldset>
              <FormikSubmitButton className="btn btn-lg btn-primary pull-xs-right">
                Sign in
              </FormikSubmitButton>
            </Form>
          </Formik>
        </div>
      </div>
    </div>
  );
}
Example #26
Source File: Login.jsx    From react-chatengine-demo with MIT License 5 votes vote down vote up
Login = () => {
  const history = useHistory();
  const [serverError, setServerError] = useState('');

  const login = ({ email, password }, { setSubmitting }) => {
    fb.auth
      .signInWithEmailAndPassword(email, password)
      .then(res => {
        if (!res.user) {
          setServerError(
            "We're having trouble logging you in. Please try again.",
          );
        }
      })
      .catch(err => {
        if (err.code === 'auth/wrong-password') {
          setServerError('Invalid credentials');
        } else if (err.code === 'auth/user-not-found') {
          setServerError('No account for this email');
        } else {
          setServerError('Something went wrong :(');
        }
      })
      .finally(() => setSubmitting(false));
  };

  return (
    <div className="auth-form">
      <h1>Login</h1>
      <Formik
        onSubmit={login}
        validateOnMount={true}
        initialValues={defaultValues}
        validationSchema={validationSchema}
      >
        {({ isValid, isSubmitting }) => (
          <Form>
            <FormField name="email" label="Email" type="email" />
            <FormField name="password" label="Password" type="password" />

            <div className="auth-link-container">
              Don't have an account?{' '}
              <span
                className="auth-link"
                onClick={() => history.push('signup')}
              >
                Sign Up!
              </span>
            </div>

            <button type="submit" disabled={!isValid || isSubmitting}>
              Login
            </button>
          </Form>
        )}
      </Formik>

      {!!serverError && <div className="error">{serverError}</div>}
    </div>
  );
}
Example #27
Source File: lead-form.js    From strapi-starter-next-corporate with MIT License 5 votes vote down vote up
LeadForm = ({ data }) => {
  const [loading, setLoading] = useState(false)

  const LeadSchema = yup.object().shape({
    email: yup.string().email().required(),
  })

  return (
    <div className="py-10 text-center">
      <h1 className="text-3xl mb-10 font-bold mb-2">{data.title}</h1>
      <div className="flex flex-col items-center">
        <Formik
          initialValues={{ email: "" }}
          validationSchema={LeadSchema}
          onSubmit={async (values, { setSubmitting, setErrors }) => {
            setLoading(true)

            try {
              setErrors({ api: null })
              await fetchAPI("/lead-form-submissions", {
                method: "POST",
                body: JSON.stringify({
                  email: values.email,
                  location: data.location,
                }),
              })
            } catch (err) {
              setErrors({ api: err.message })
            }

            setLoading(false)
            setSubmitting(false)
          }}
        >
          {({ errors, touched, isSubmitting }) => (
            <div>
              <Form className="flex flex-col md:flex-row gap-4">
                <Field
                  className="text-base focus:outline-none py-4 md:py-0 px-4 border-2 rounded-md"
                  type="email"
                  name="email"
                  placeholder={data.emailPlaceholder}
                />
                <Button
                  type="submit"
                  button={data.submitButton}
                  disabled={isSubmitting}
                  loading={loading}
                />
              </Form>
              <p className="text-red-500 h-12 text-sm mt-1 ml-2 text-left">
                {(errors.email && touched.email && errors.email) || errors.api}
              </p>
            </div>
          )}
        </Formik>
      </div>
    </div>
  )
}
Example #28
Source File: AccountEditForm.js    From umami with MIT License 5 votes vote down vote up
export default function AccountEditForm({ values, onSave, onClose }) {
  const { post } = useApi();
  const [message, setMessage] = useState();

  const handleSubmit = async values => {
    const { ok, data } = await post('/account', values);

    if (ok) {
      onSave();
    } else {
      setMessage(
        data || <FormattedMessage id="message.failure" defaultMessage="Something went wrong." />,
      );
    }
  };

  return (
    <FormLayout>
      <Formik
        initialValues={{ ...initialValues, ...values }}
        validate={validate}
        onSubmit={handleSubmit}
      >
        {() => (
          <Form>
            <FormRow>
              <label htmlFor="username">
                <FormattedMessage id="label.username" defaultMessage="Username" />
              </label>
              <div>
                <Field name="username" type="text" />
                <FormError name="username" />
              </div>
            </FormRow>
            <FormRow>
              <label htmlFor="password">
                <FormattedMessage id="label.password" defaultMessage="Password" />
              </label>
              <div>
                <Field name="password" type="password" />
                <FormError name="password" />
              </div>
            </FormRow>
            <FormButtons>
              <Button type="submit" variant="action">
                <FormattedMessage id="label.save" defaultMessage="Save" />
              </Button>
              <Button onClick={onClose}>
                <FormattedMessage id="label.cancel" defaultMessage="Cancel" />
              </Button>
            </FormButtons>
            <FormMessage>{message}</FormMessage>
          </Form>
        )}
      </Formik>
    </FormLayout>
  );
}
Example #29
Source File: MultistepForm.jsx    From awesome-react-starter with MIT License 5 votes vote down vote up
MultistepForm = () => {
  const [step, setStep] = useState(0);
  const previous = () => setStep((step) => step - 1);
  const next = () => setStep((step) => step + 1);

  const renderStep = (step) => {
    const formProps = {};
    formProps.previous = previous;
    formProps.next = next;

    switch (step) {
      case 0:
        return <StepOne {...formProps} />;
      case 1:
        return <StepTwo {...formProps} />;
      case 2:
        return <StepThree {...formProps} />;
      default:
        return null;
    }
  };

  const stepValidation = (step) => {
    return validationSchema[step];
  };
  const stepValues = (step) => {
    return initialValues[step];
  };
  const handleSubmit = () => {
    const isLastStep = step === 2;
    if (isLastStep) {
      toaster.success('Multi step Formik form finished successfully');
    } else {
      return next();
    }
  };

  return (
    <article className="bg-white py-4">
      <HeaderSteps step={step} />
      <Formik
        validationSchema={stepValidation(step)}
        initialValues={stepValues(step)}
        onSubmit={handleSubmit}
      >
        <Form className="p-4">{renderStep(step)}</Form>
      </Formik>
    </article>
  );
}