formik#Formik JavaScript Examples

The following examples show how to use formik#Formik. 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: index.js    From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 6 votes vote down vote up
MyProjectsCreate = ({ setUploadImageStatus }) => {
  return (
    <div className="myproject-layout">
      <div className="myproject-layout-title">
        <HeadingTwo text="Create a project" color="#084892" />
      </div>
      <div className="myproject-layout-formik">
        <Formik>
          <form>
            <div className="layout-formik-input">
              <InputLabel text="Project Name" className="input-label">
                <InputTextField placeholder="e.g Course Name" className="input-field" />
              </InputLabel>
            </div>
            <div className="layout-formik-input">
              <InputLabel text="What is your project about?" className="input-label">
                <InputTextField placeholder="Write a brief description of your project" className="input-field" />
              </InputLabel>
            </div>
            <div className="layout-formik-uploadimage">
              <UploadImage setUploadImageStatus={setUploadImageStatus} />
            </div>
          </form>
        </Formik>
      </div>
      <div className="myproject-button">
        <Buttons text="Next" primary={true} width="126px" height="43px" hover={true} />
      </div>
    </div>
  );
}
Example #2
Source File: LocationField.spec.js    From carpal-fe with MIT License 6 votes vote down vote up
test("should Render Location Field Component", () => {

    const wrapper = render(
        <Formik>
            <LocationField />
        </Formik>
    );

});
Example #3
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 #4
Source File: AddAllergens.test.js    From neighborhood-chef-fe with MIT License 6 votes vote down vote up
describe("Test AddAllergens component", () => {
  let AddAllergensComponent;
  beforeEach(() => {
    AddAllergensComponent = render(
      <Formik>
        <AddAllergens values={{ allergens: [] }} />
      </Formik>
    );
  });

  test("AddAllergens component renders", () => {
    expect(AddAllergensComponent.getByText(/Allergens/i));
  });
});
Example #5
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 #6
Source File: DiagnosisContainer.js    From web with GNU General Public License v3.0 6 votes vote down vote up
DiagnosisContainer = () => {
  const dispatch = useDispatch();

  const saveRiskTest = (triage, evidence, allQuestions) => {
    const { triage_level: triageLevel, description } = triage;
    const data = {
      allQuestions: allQuestions.filter(item => item),
      evidence,
      triageLevel,
      description
    };

    dispatch(addRiskTest(data));
  };

  const finish = (evidence, isElderly, allQuestions) => {
    const data = {
      isElderly,
      evidence
    };
    dispatch(fetchTriage(data)).then(triage => saveRiskTest(triage, evidence, allQuestions));
  };

  return (
    <Formik initialValues={DIAGNOSIS_FORM_INITIAL_VALUES}>
      <Form onFinish={finish} />
    </Formik>
  );
}
Example #7
Source File: ChangeWorker.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
function ChangeWorker(props) {
  const onSubmit = (stakeValues) => {
    if (props.onChangeWorker) {
      props.onChangeWorker(stakeValues);
    }
  };
  return <Formik onSubmit={onSubmit} initialValues={{ workerAddress: props.worker ? props.worker : '' }} validationSchema={validationSchema}>
    {({
      handleSubmit,
      handleChange,
      handleBlur,
      values,
      touched,
      isValid,
      errors,
    }) => (
      <Form onSubmit={handleSubmit}>
        <Form.Group as={Row}>
          <Form.Label column sm={2} htmlFor="worker-address">
            Worker
          </Form.Label>
          <Col sm={10}>
            <Form.Control id="worker-address" type="text" name="workerAddress" onChange={handleChange} value={values.workerAddress} />
            <Form.Control.Feedback type="invalid" style={{ display: errors.workerAddress ? 'inline' : 'none' }}>{errors.workerAddress}</Form.Control.Feedback>
          </Col>
        </Form.Group>
        <div className="d-flex justify-content-center">
          <Button type="submit"  disabled={!isValid}>Set worker</Button>
        </div>
      </Form>
    )}
  </Formik>;
}
Example #8
Source File: AnimationInput.test.js    From UltimateApp with MIT License 6 votes vote down vote up
describe('AnimationInput', () => {
  // fake NavigationContext value data
  const navContext = {
    isFocused: () => true,
    // addListener returns an unscubscribe function.
    addListener: jest.fn(() => jest.fn()),
  };

  it('renders correctly', () => {
    const { toJSON } = render(
      <NavigationContext.Provider value={navContext}>
        <Formik initialValues={{ title: 'My title' }}>
          <AnimationInput fieldName="title" label="Title" />
        </Formik>
      </NavigationContext.Provider>,
    );
    expect(toJSON()).toMatchSnapshot();
  });
});
Example #9
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 #10
Source File: index.js    From puente-reactnative-collect with MIT License 6 votes vote down vote up
StorePinCode = ({ navigation }) => (
  <Formik
    initialValues={{ pincode: '' }}
    onSubmit={(values, actions) => {
      storeData(values.pincode, 'pincode').then(() => {
        navigation.navigate('Root');
      });

      setTimeout(() => {
        actions.setSubmitting(false);
      }, 1000);
    }}
  >
    {(formikProps) => (
      <>
        <FormInput
          label={I18n.t('pinCode.storePinCode.enterPinCode')}
          formikProps={formikProps}
          formikKey="pincode"
          placeholder="123456"
          keyboardType="numeric"
        />
        {formikProps.isSubmitting ? (
          <ActivityIndicator />
        ) : (
          <Button onPress={formikProps.handleSubmit}>
            <Text>{I18n.t('global.submit')}</Text>
          </Button>
        )}
      </>
    )}
  </Formik>
)
Example #11
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 #12
Source File: createproject.js    From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 5 votes vote down vote up
MyProjectsCreate = ({ setUploadImageStatus }) => {
  return (
    <div className="myproject-layout">
      <div className="myproject-layout-title">
        <HeadingTwo text="Create a project" color="#084892" />
      </div>
      <div className="myproject-layout-formik">
        <Formik>
          <form>
            <div className="layout-formik-input">
              <InputLabel text="Project Name" className="input-label">
                <InputTextField
                  placeholder="e.g Course Name"
                  className="input-field"
                />
              </InputLabel>
            </div>
            <div className="layout-formik-input">
              <InputLabel
                text="What is your project about?"
                className="input-label"
              >
                <InputTextField
                  placeholder="Write a brief description of your project"
                  className="input-field"
                />
              </InputLabel>
            </div>
            <div className="layout-formik-input">
              <InputLabel text="Visibility type" className="input-label">
                <select>
                  <option>Private</option>
                </select>
              </InputLabel>
            </div>
            <div className="layout-formik-uploadimage">
              <UploadImage setUploadImageStatus={setUploadImageStatus} />
            </div>
          </form>
        </Formik>
      </div>
      <div className="myproject-button">
        <Buttons
          text="Create Project"
          primary={true}
          width="189px"
          height="43px"
          hover={true}
        />
      </div>
    </div>
  );
}
Example #13
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 #14
Source File: Login.jsx    From ashteki with GNU Affero General Public License v3.0 5 votes vote down vote up
Login = (props) => {
    const { t } = useTranslation();

    const schema = yup.object({
        username: yup.string().required(t('You must specify a username')),
        password: yup.string().required(t('You must specify a password'))
    });

    return (
        <Formik validationSchema={schema} onSubmit={props.onSubmit} initialValues={initialValues}>
            {(formProps) => (
                <Form
                    onSubmit={(event) => {
                        event.preventDefault();
                        formProps.handleSubmit(event);
                    }}
                >
                    <Form.Row>
                        <Form.Group as={Col} lg='6' controlId='formGridUsername'>
                            <Form.Label>{t('Username')}</Form.Label>
                            <Form.Control
                                name='username'
                                type='text'
                                placeholder={t('Enter your username')}
                                value={formProps.values.username}
                                onChange={formProps.handleChange}
                                onBlur={formProps.handleBlur}
                                isInvalid={
                                    formProps.touched.username && !!formProps.errors.username
                                }
                            />
                            <Form.Control.Feedback type='invalid'>
                                {formProps.errors.username}
                            </Form.Control.Feedback>
                        </Form.Group>
                        <Form.Group as={Col} controlId='formGridPassword'>
                            <Form.Label>{t('Password')}</Form.Label>
                            <Form.Control
                                name='password'
                                type='password'
                                placeholder={t('Enter your password')}
                                value={formProps.values.password}
                                onChange={formProps.handleChange}
                                onBlur={formProps.handleBlur}
                                isInvalid={
                                    formProps.touched.password && !!formProps.errors.password
                                }
                            />
                            <Form.Control.Feedback type='invalid'>
                                {formProps.errors.password}
                            </Form.Control.Feedback>
                        </Form.Group>
                    </Form.Row>
                    <Link href='/forgot'>
                        <Trans>Forgotten your password?</Trans>
                    </Link>

                    <div className='text-center'>
                        <Button variant='primary' type='submit'>
                            {t('Login')}
                        </Button>
                    </div>
                </Form>
            )}
        </Formik>
    );
}
Example #15
Source File: LabelField.spec.js    From carpal-fe with MIT License 5 votes vote down vote up
describe("LabelField", () => {
    test("Renders without crashing", () => {
        const div = document.createElement("div");

        ReactDOM.render(
            <Provider store={store}>
                <Router>
                    <Formik>
                        <LabelField
                            touched={null}
                            error={null}
                            type="text"
                            name="first_name"
                            placeholder="First Name"
                        />
                    </Formik>
                </Router>
            </Provider>,
            div
        );
    });

    test("Renders props correctly", () => {
        const { getByPlaceholderText } = rtl.render(
            <Provider store={store}>
                <Router>
                    <Formik>
                        <LabelField
                            touched={null}
                            error={null}
                            type="text"
                            name="first_name"
                            placeholder="First Name"
                        />
                    </Formik>
                </Router>
            </Provider>
        );
        expect(getByPlaceholderText("First Name")).toBeVisible();
        expect(getByPlaceholderText("First Name")).toHaveClass("formik-fields");
        expect(getByPlaceholderText("First Name")).toHaveAttribute("type", "text");
        expect(getByPlaceholderText("First Name")).toHaveAttribute("name", "first_name");
    });
});
Example #16
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 #17
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 #18
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 #19
Source File: form.js    From proof-of-humanity-web with MIT License 5 votes vote down vote up
export default function Form({
  createValidationSchema,
  onSubmit,
  sx,
  children,
  ...rest
}) {
  const { web3 } = useWeb3();
  const validationSchema = useMemo(
    () =>
      object(
        createValidationSchema({
          boolean,
          eth() {
            const initialValue = Web3.utils.toBN("");
            initialValue.toString = () => "";
            initialValue.originalString = "";
            return new ETH().default(initialValue);
          },
          file() {
            return new File().nullable();
          },
          string() {
            return string().default("");
          },
          web3,
        })
      ),
    [createValidationSchema, web3]
  );
  return (
    <ValidationSchemaContext.Provider value={validationSchema}>
      <Formik
        initialValues={validationSchema.default()}
        validationSchema={validationSchema}
        onSubmit={(values, formikBag) =>
          onSubmit(validationSchema.cast(values), formikBag)
        }
        {...rest}
      >
        {(props) => (
          <FocusOnFirstError>
            <Box as={_Form} variant="form" sx={sx}>
              {typeof children === "function" ? children(props) : children}
            </Box>
          </FocusOnFirstError>
        )}
      </Formik>
    </ValidationSchemaContext.Provider>
  );
}
Example #20
Source File: DailyDataContainer.js    From web with GNU General Public License v3.0 5 votes vote down vote up
DailyDataContainer = () => {
  const dispatch = useDispatch();
  const daily = useSelector(state => state.daily);
  const { getParam, goBack } = useNavigation();

  const goHome = () => goBack();

  const id = getParam('id');

  const dailyData = daily[id];

  const validationSchema = Yup.object().shape({
    [FIELD_TEMPERATURE]: Yup.number()
      .min(35, 'form_text15')
      .max(45, 'form_text16')
  });

  const initialValues = {
    [FIELD_TEMPERATURE]: (dailyData && dailyData.data[FIELD_TEMPERATURE]) || '',
    [FIELD_RUNNY_NOSE]: (dailyData && dailyData.data[FIELD_RUNNY_NOSE]) || VALUE_SYMPTOM_LEVEL_1,
    [FIELD_COUGH]: (dailyData && dailyData.data[FIELD_COUGH]) || VALUE_SYMPTOM_LEVEL_1,
    [FIELD_CHILLS]: (dailyData && dailyData.data[FIELD_CHILLS]) || VALUE_SYMPTOM_LEVEL_1,
    [FIELD_MUSCLE_PAIN]: (dailyData && dailyData.data[FIELD_MUSCLE_PAIN]) || VALUE_SYMPTOM_LEVEL_1,
    [FIELD_CONTACTS]: (dailyData && dailyData.data[FIELD_CONTACTS]) || '',
    [FIELD_TIME]: (dailyData && dailyData.data[FIELD_TIME]) || new Date()
  };

  const [mode, setMode] = useState(dailyData ? DAILY_DATA_MODE.VIEW : DAILY_DATA_MODE.CREATE);

  const handleSubmit = form => {
    if (!isEditMode(mode)) {
      dispatch(addDaily({ data: form })).then(goHome);
      return;
    }

    dispatch(updateDaily({ data: form }, id)).then(goHome);
  };

  return (
    <Formik initialValues={initialValues} onSubmit={handleSubmit} validationSchema={validationSchema}>
      <DailyData mode={mode} setMode={setMode} />
    </Formik>
  );
}
Example #21
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 #22
Source File: index.js    From community-front-end with MIT License 5 votes vote down vote up
AddAnswer = ({ id, tags, setQuestion }) => {
  const { authAxios } = useContext(FetchContext)
  const { isAuthenticated } = useContext(AuthContext)
  const { handleComponentVisible } = useContext(ModalContext)

  const [loading, setLoading] = useState(false)

  return (
    <Formik
      initialValues={{ text: '' }}
      onSubmit={async (values, { setStatus, resetForm }) => {
        setLoading(true)
        try {
          const { data } = await authAxios.post(`/answer/${id}`, values)
          setQuestion(data)
          resetForm({})
        } catch (error) {
          setStatus(error.response.data.message)
        }
        setLoading(false)
      }}
      validationSchema={Yup.object({
        text: Yup.string()
          .required('Body is missing.')
          .min(30, 'Body must be at least 30 characters.')
          .max(30000, 'Body cannot be longer than 30000 characters.')
      })}
    >
      {({
        values,
        errors,
        touched,
        status,
        handleChange,
        handleBlur,
        handleSubmit,
        isSubmitting,
      }) => (
        <form className={styles.container} onSubmit={handleSubmit}>
          <h2>Your answer</h2>
          <TextArea
            name="text"
            autoComplete="off"
            value={values.text}
            onChange={handleChange}
            onBlur={handleBlur}
            hasError={touched.text && errors.text}
            errorMessage={errors.text && errors.text}
            className={styles.textarea}
          />
          <p className={styles.status}>{status}</p>
          <div className={styles.button}>
            <Button
              type="submit"
              primary
              isLoading={loading}
              disabled={isSubmitting}
              onClick={() => !isAuthenticated() && handleComponentVisible(true, 'signup')}
            >
              Post Your Answer
            </Button>
          </div>
          <h3>
            Browse other questions tagged &nbsp;
            {tags.map((tag) => (
              <Tag key={tag}>{tag}</Tag>
            ))}
            or &nbsp;
            <Link href="/questions/ask" as="/questions/ask">
              <a>ask your own question.</a>
            </Link>
          </h3>
        </form>
      )}
    </Formik>
  )
}
Example #23
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 #24
Source File: Recording-Editor.js    From aws-amplify-quick-notes with MIT No Attribution 5 votes vote down vote up
RecordingEditor = props => (
  <Dialog onDismiss={props.onDismiss}>
    <Title>{props.title ? "Edit Note" : "Create Note"}</Title>
    <Formik
      initialValues={{
        title: props.title || "",
        text: props.text
      }}
      onSubmit={(values, { setSubmitting, resetForm }) => {
        props.onSave({
          title: values.title || `${values.text.substr(0, 20)}...`,
          text: values.text
        });
        setSubmitting(false);
        resetForm();
        props.onDismiss();
      }}
    >
      {({ values, handleSubmit, isSubmitting, handleChange }) => (
        <form onSubmit={handleSubmit}>
          <FormInputs>
            <InputContainer>
              <StyledLabel htmlFor="title">Title</StyledLabel>
              <StyledInput
                type="text"
                name="title"
                value={values.title}
                onChange={handleChange}
              />
            </InputContainer>

            <InputContainer>
              <StyledLabel htmlFor="text">Note</StyledLabel>
              <StyledTextarea
                name="text"
                value={values.text}
                onChange={handleChange}
              />
            </InputContainer>
          </FormInputs>

          <Actions>
            <StyledButton
              onClick={() => {
                props.onDismiss();
              }}
              style={{ marginRight: "8px" }}
            >
              Cancel
            </StyledButton>
            <StyledButton type="submit" disabled={isSubmitting}>
              {isSubmitting ? "Saving..." : "Save"}
            </StyledButton>
          </Actions>
        </form>
      )}
    </Formik>
  </Dialog>
)
Example #25
Source File: Forgot.js    From reactnative-best-practice with MIT License 5 votes vote down vote up
export default function ForgotScreen() {
  const navigation = useNavigation();
  const {navigate} = navigation;

  function _onSend() {
    navigate('Login');
  }

  function _navigateLogin() {
    navigate('Login');
  }

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.greeting}>Forgot password?</Text>
      <View style={{height: 72}} />
      <Formik
        initialValues={{
          phone: '0704498756',
        }}
        validationSchema={ForgotSchema}
        onSubmit={values => {
          _onSend(values);
        }}>
        {({
          handleChange,
          handleBlur,
          handleSubmit,
          values,
          errors,
          touched,
        }) => (
          <View>
            <View style={styles.form}>
              <Text style={styles.inputTitle}>Phone Number</Text>
              <TextInput
                style={styles.input}
                onChangeText={handleChange('phone')}
                onBlur={handleBlur('phone')}
                value={values.phone}
              />
              {errors.phone && touched.phone ? (
                <Text style={styles.error}>{errors.phone}</Text>
              ) : null}
            </View>
            <TouchableOpacity style={styles.button} onPress={handleSubmit}>
              <Text style={styles.buttonText}>Reset Password</Text>
            </TouchableOpacity>
          </View>
        )}
      </Formik>

      <View
        style={{
          flexDirection: 'row',
          alignSelf: 'center',
          marginTop: 32,
        }}>
        <Text style={{color: '#414959'}}>Back to </Text>
        <TouchableOpacity onPress={_navigateLogin}>
          <Text style={styles.signInText}>Sign In</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}
Example #26
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 #27
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 #28
Source File: AddStake.js    From stake-nucypher with GNU Affero General Public License v3.0 5 votes vote down vote up
function AddStake(props) {
  const onSubmit = (stakeValues) => {
    if (props.onAddStake) {
      props.onAddStake(stakeValues);
    }
  };
  return <Formik onSubmit={onSubmit} initialValues={{ infiniteApproval: false }} validationSchema={validationSchema}>
    {({
      handleSubmit,
      handleChange,
      handleBlur,
      values,
      touched,
      isValid,
      errors,
      dirty
    }) => (
      <Form onSubmit={handleSubmit}>
        <Form.Group as={Row}>
          <Form.Label column sm={4} htmlFor="stake-value">
            Stake value
          </Form.Label>
          <Col sm={8}>
            <Form.Control id="stake-value" type="number" name="stakeValue" onChange={handleChange} value={values.value} />
            <div className="feedback-placeholder">
              <Form.Control.Feedback type="invalid" style={{ display: errors.stakeValue && dirty ? 'inline' : 'none' }}>{errors.stakeValue}</Form.Control.Feedback>
            </div>
          </Col>
        </Form.Group>
        <Form.Group as={Row}>
          <Form.Label column sm={4} htmlFor="stakeDuration">
            Stake duration
          </Form.Label>
          <Col sm={8}>
            <Form.Control id="stakeDuration" type="number" name="stakeDuration" onChange={handleChange} value={values.duration} />
            <div className="feedback-placeholder">
              <Form.Control.Feedback type="invalid" style={{ display: errors.stakeDuration && dirty ? 'inline' : 'none' }}>{errors.stakeDuration}</Form.Control.Feedback>
            </div>
          </Col>
        </Form.Group>
        <Form.Group as={Row}>
          <Col sm={{ span: 8, offset: 4 }}>
            <Form.Check label="Infinite approval" name="infiniteApproval" defaultChecked={values.infiniteApproval} onChange={handleChange} value={values.infiniteApproval} />
          </Col>
        </Form.Group>
        <div className="d-flex justify-content-center">
          <Button type="submit" disabled={!isValid}>Stake</Button>
        </div>
      </Form>
    )}
  </Formik>;
}
Example #29
Source File: Input.test.js    From UltimateApp with MIT License 5 votes vote down vote up
describe('Input', () => {
  it('renders correctly', () => {
    const { toJSON } = render(
      <Formik initialValues={{ title: 'My title' }}>
        <Input fieldName="title" label="Title" />
      </Formik>,
    );
    expect(toJSON()).toMatchSnapshot();
  });

  it('renders correctly when required', () => {
    const { toJSON } = render(
      <Formik initialValues={{ title: 'My title' }}>
        <Input fieldName="title" label="Title" required />
      </Formik>,
    );
    expect(toJSON()).toMatchSnapshot();
  });

  it('renders correctly when multiline', () => {
    const { toJSON } = render(
      <Formik initialValues={{ title: 'My title' }}>
        <Input fieldName="title" label="Title" multiline />
      </Formik>,
    );
    expect(toJSON()).toMatchSnapshot();
  });

  it('renders correctly when there is an error', async () => {
    const { toJSON, getByTestId, getByDisplayValue, getByText } = render(
      <Formik
        initialValues={{ title: 'My title' }}
        validationSchema={Yup.object({ title: Yup.string().required().min(1000, 'Invalid title') })}
      >
        {({ handleSubmit }) => (
          <>
            <Input fieldName="title" label="Title" />
            <TouchableOpacity onPress={handleSubmit} testID="submit" />
          </>
        )}
      </Formik>,
    );

    expect(getByDisplayValue('My title')).toBeDefined();

    fireEvent.changeText(getByTestId('input-title'), 'new title');

    expect(getByDisplayValue('new title')).toBeDefined();

    await waitFor(() => {
      fireEvent.press(getByTestId('submit'));
    });

    expect(getByText('Invalid title')).not.toBeNull();
    expect(toJSON()).toMatchSnapshot();
  });
});