react-hook-form#useForm JavaScript Examples

The following examples show how to use react-hook-form#useForm. 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: Form.js    From schematic-capture-fe with MIT License 6 votes vote down vote up
CreateNewProject = () => {
  const { handleSubmit, register } = useForm();
  const params = useParams();
  const dispatch = useDispatch();
  const history = useHistory();

  const onAddNewProject = (data) => {
    dispatch(addNewProject(data, params.id, history));
  };

  return (
    <div>
      <form onSubmit={handleSubmit(onAddNewProject)}>
        <p>Please enter the project name below:</p>
        <div>
          {/*<form onSubmit={handleSubmit(onAddNewProject)}>*/}
          {/*  <StyledFields fields={schema} register={register} errors={errors} />*/}
          {/*  <button type="submit">Save</button>*/}
          {/*  <Link to={`/client/${params.id}`}>Cancel</Link>*/}
          {/*</form>*/}
          <input
            type="string"
            name="name"
            id="name"
            placeholder="Project Name"
            aria-label="Project Name"
            ref={register({ required: true })}
          />
        </div>
        <div>
          <button variant="primary" submit="button" btnBlock>
            Create
          </button>
        </div>
      </form>
    </div>
  );
}
Example #2
Source File: Form.js    From ponce-tournois-mario-kart with MIT License 6 votes vote down vote up
function Form({ children, onSubmit, ...rest }) {
    const { handleSubmit, ...formValues } = useForm();

    return (
        <form onSubmit={handleSubmit(onSubmit)} {...rest}>
            <FormContext.Provider value={formValues}>
                {children}
            </FormContext.Provider>
        </form>
    );
}
Example #3
Source File: SignIn.jsx    From saasgear with MIT License 6 votes vote down vote up
function SignIn() {
  useDocumentHeader({ title: 'Sign In' });
  const { register, handleSubmit, errors: formErrors } = useForm({
    resolver: yupResolver(SignInSchema),
  });
  const [loginMutation, { error, loading }] = useMutation(loginQuery);
  const history = useHistory();

  async function onSubmit(params) {
    try {
      const { data } = await loginMutation({ variables: params });
      if (data?.login) {
        history.push('/');
      }
    } catch (e) {
      console.log(e);
    }

    return false;
  }

  return (
    <SignUpFormWrapper>
      <SignUpFormLeft>
        <SignInForm
          onSubmit={handleSubmit(onSubmit)}
          register={register}
          formErrors={formErrors}
          apiError={error?.message}
          isSubmitting={loading}
        />
      </SignUpFormLeft>
      <SignUpAds>
        <AuthAdsArea />
      </SignUpAds>
    </SignUpFormWrapper>
  );
}
Example #4
Source File: index.jsx    From product-collector with MIT License 6 votes vote down vote up
SearchTrends = () => {
  const { register, handleSubmit, errors } = useForm();

  const onSubmit = (data) => {
    const { search } = data;
    Router.push({
      pathname: '/explore',
      query: { search },
    });
  };

  return (
    <div className={styles.searchTrends}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <h1>Consulta las tendencias</h1>
        <div>
          <input
            type='text'
            name='search'
            placeholder='Ingrese el producto a buscar'
            ref={register({ required: true })}
          />
          <Button type='submit'>Buscar</Button>
        </div>
        {errors.search && (
          <div className={styles.error}>El producto es requerida</div>
        )}
      </form>
      <div className={styles.footer}>
        <img src='images/datviz.png' alt='Datviz' />
      </div>
    </div>
  );
}
Example #5
Source File: already-migrated.input.js    From codemod with MIT License 6 votes vote down vote up
Form = () => {
  const { formState: {
    errors,
  } } = useForm();

  return (
    <form>
      <span>{errors.username.message}</span>
    </form>
  );
}
Example #6
Source File: BookForm.jsx    From react-query-3 with GNU General Public License v3.0 6 votes vote down vote up
BookForm = ({ defaultValues, onFormSubmit, isLoading }) => {
  const { register, handleSubmit } = useForm({ defaultValues });

  const onSubmit = handleSubmit((data) => {
    onFormSubmit(data)
  })

  return (
    <form onSubmit={onSubmit}>
      <Box sx={{ marginBottom: 3 }}>
        <Label htmlFor="title">Title</Label>
        <Input ref={register} id="title" name="title" type="text" />
      </Box>
      <Box sx={{ marginBottom: 3 }}>
        <Label htmlFor="author">Author</Label>
        <Input ref={register} id="author" name="author" type="text" />
      </Box>
      <Button variant="primary" mr={2}>
        { isLoading ? <Loader type="ThreeDots" color="#fff" height={10} /> : "Submit" }
      </Button>
    </form>
  );
}
Example #7
Source File: Step3.js    From ultimate-react-hook-form-form with MIT License 6 votes vote down vote up
Step3 = () => {
  const history = useHistory();
  const { data, setValues } = useData();
  const { control, handleSubmit } = useForm({
    defaultValues: {
      files: data.files,
    },
  });

  const onSubmit = (data) => {
    history.push("./result");
    setValues(data);
  };

  return (
    <MainContainer>
      <Typography component="h2" variant="h5">
        ? Step 3
      </Typography>
      <Form onSubmit={handleSubmit(onSubmit)}>
        <FileInput name="files" control={control} />
        <PrimaryButton>Next</PrimaryButton>
      </Form>
    </MainContainer>
  );
}
Example #8
Source File: DeploymentNameModal.js    From akashlytics-deploy with GNU General Public License v3.0 5 votes vote down vote up
DeploymentNameModal = ({ dseq, onClose, onSaved, getDeploymentName }) => {
  const classes = useStyles();
  const formRef = useRef();
  const { enqueueSnackbar } = useSnackbar();
  const { handleSubmit, control, setValue } = useForm({
    defaultValues: {
      name: ""
    }
  });

  useEffect(() => {
    if (dseq) {
      const name = getDeploymentName(dseq);
      setValue("name", name || "");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dseq, getDeploymentName]);

  const onSaveClick = (event) => {
    event.preventDefault();
    formRef.current.dispatchEvent(new Event("submit", { cancelable: true, bubbles: true }));
  };

  function onSubmit({ name }) {
    updateDeploymentLocalData(dseq, { name: name });

    enqueueSnackbar(<Snackbar title="Success!" iconVariant="success" />, { variant: "success", autoHideDuration: 1000 });

    onSaved();
  }

  return (
    <Dialog open={!!dseq} onClose={onClose} maxWidth="xs" fullWidth>
      <DialogTitle>Change Deployment Name {dseq ? `(${dseq})` : ""}</DialogTitle>
      <DialogContent dividers className={classes.dialogContent}>
        <form onSubmit={handleSubmit(onSubmit)} ref={formRef}>
          <FormControl fullWidth>
            <Controller
              control={control}
              name="name"
              render={({ field }) => {
                return <TextField {...field} autoFocus type="text" variant="outlined" label="Name" />;
              }}
            />
          </FormControl>
        </form>
      </DialogContent>
      <DialogActions className={classes.dialogActions}>
        <Button onClick={onClose}>Close</Button>
        <Button variant="contained" color="primary" onClick={onSaveClick}>
          Save
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #9
Source File: Login.js    From Encon-fe with MIT License 5 votes vote down vote up
Login = () => {
  const { handleSubmit, register, errors, reset } = useForm();
  const baseUrl = 'https://encon-be.herokuapp.com/api';
  // const [loginError, setLoginError] = useState();
  const history = useHistory();

  const onLoginSubmit = (data) => {
    axios
      .post(baseUrl + '/auth/login', {
        email: data.email,
        password: data.password,
      })
      .then((res) => {
        reset();
        localStorage.setItem('AUTH_TOKEN', res.data.token);
        localStorage.setItem('USER_ID', res.data.Data.id);
        localStorage.setItem('USER_NAME', res.data.Data.name);
        localStorage.setItem('USER_LOCATION', res.data.Data.state);
        history.push('/profile');
      })
      .catch((err) => {
        // setLoginError('Login Error: ' + err.response.data.error.message);
      });
  };

  return (
    <div className='login-container'>
      <HeaderAlt />
      <form className='loginForm' onSubmit={handleSubmit(onLoginSubmit)}>
        <label htmlFor='email' className='label'>
          Email
        </label>
        <input
          type='email'
          name='email'
          ref={register({ required: true, pattern: /^\S+@\S+$/i })}
        />
        <ErrorMessage error={errors.email} />
        {errors.email && errors.email.message}
        <label htmlFor='password' className='label'>
          Password
        </label>
        <input
          type='password'
          name='password'
          ref={register({ required: true })}
        />
        <ErrorMessage error={errors.password} />
        <button className='app-buttons' type='submit' data-testid='sign in'>
          Sign In
        </button>
        {/* <div>{loginError}</div> */}
      </form>
    </div>
  );
}
Example #10
Source File: FirstLoginForm.js    From schematic-capture-fe with MIT License 5 votes vote down vote up
FirstLoginForm = (props) => {
  const { register, handleSubmit, errors } = useForm()
  const dispatch = useDispatch()
  const history = useHistory()
  const { firstLogin } = dispatchers

  const onSubmit = (data) => {
    dispatch(firstLogin(data = {...data, token: props.match.params.userToken }, history))
  }

  return (
    <FormContainer>
      <form className="white" onSubmit={handleSubmit(onSubmit)}>
        <Signin className="signin">First Time Log-in</Signin>
        <FormGroup>
          <StyledField
            data-password
            type="password"
            name="newPassword"
            id="newPassword"
            placeholder="New Password"
            aria-label="New Password"
            aria-invalid={errors.password ? "true" : "false"}
            aria-describedby="error-password-required"
            ref={register({ required: true })}
          />
          {errors.password && errors.password.type === "required" && (
            <FieldError id="error-password-required">
              That's an incorrect password. Try again.
            </FieldError>
          )}
        </FormGroup>
        <FormGroup>
          <label> Select Security Question 
          <StyledSelect
            name="newQuestion" 
            label="Select Security Question"
            ref={register({ required: true })}>
            <option value="What was your childhood nickname?">What was your childhood nickname?</option>
            <option value=" In what city did you meet your spouse/significant other?"> In what city did you meet your spouse/significant other?</option>
            <option value=" What is the name of your favorite childhood friend?"> What is the name of your favorite childhood friend?</option>
            <option value="What street did you live on in third grade?">What street did you live on in third grade?</option>
            <option value="What is your oldest sibling's middle name?">What is your oldest sibling's middle name?</option>
            <option value="In what city or town was your first job?">In what city or town was your first job?</option>
          </StyledSelect>
          </label>
        </FormGroup>
        <FormGroup>
          <StyledField
          // @TODO: Finish Field for security answer:
          name="newAnswer"
          id="answer"
          ref={register({ required: true })}
          placeholder="Answer to Security Question"
          aria-label="Answer to Security Question"
          />
        </FormGroup>
        <FormRow>
          <FormColumn>
            <Button data-button-continue variant="primary" type="submit">
              Continue
            </Button>
          </FormColumn>
          <FormColumn style={{ textAlign: "right" }}>
            <Link to="/forgotpassword">Forgot password?</Link>
          </FormColumn>
        </FormRow>
      </form>
    </FormContainer>
  )
}
Example #11
Source File: AccountForm.js    From app with MIT License 5 votes vote down vote up
function AccountForm({ account, onSubmit }) {
  const classes = useStyles();
  const {
    register,
    handleSubmit,
    errors,
    formState: { isSubmitting, isValid },
  } = useForm({
    mode: 'onChange',
    nativeValidation: false,
    defaultValues: account,
  });

  return (
    <form className={classes.root} onSubmit={handleSubmit(onSubmit)}>
      <div className={classes.fields}>
        <TextField
          name="displayName"
          label="Display Name"
          margin="normal"
          inputRef={register}
          fullWidth
        />
        <TextField
          type="email"
          name="email"
          label="Email"
          margin="normal"
          fullWidth
          inputRef={register({
            required: true,
            validate: validateEmail,
          })}
          error={!!errors.email}
          helperText={errors.email && 'Email must be valid'}
        />
      </div>
      {!!account && !!account.providerData && (
        <div>
          <Typography variant="h6">Linked Accounts</Typography>
          <ProviderDataForm providerData={account.providerData} />
        </div>
      )}
      <div className={classes.settings}>
        <Typography variant="h5">Notification Settings</Typography>
        <FormControlLabel
          control={
            <Switch
              name="emailNotifications"
              color="primary"
              inputRef={register}
              defaultChecked={account?.emailNotifications || false}
            />
          }
          label="Email Notifications"
        />
        <FormControlLabel
          control={
            <Switch
              name="browserNotifications"
              color="primary"
              inputRef={register}
              defaultChecked={account?.browserNotifications || false}
            />
          }
          label="Browser Notifications"
        />
      </div>
      <Button
        color="primary"
        type="submit"
        variant="contained"
        disabled={isSubmitting || !isValid}>
        {isSubmitting ? 'Saving' : 'Save'}
      </Button>
    </form>
  );
}
Example #12
Source File: Form.js    From react-powerhouse with MIT License 5 votes vote down vote up
// Reusable Form Component
function Form({ template, onSubmit, watchFields, validate }) {

    let { register, handleSubmit, errors, watch, setError, clearErrors } = useForm();
    let { title, fields } = template;

    let watchValues = watch(watchFields);
    validate(watchValues, { errors, setError, clearErrors });

    const renderFields = (fields) => {
        return fields.map(field => {
            let { title, type, name, validationProps, dynamic } = field;

            let showField = dynamic ? watchValues[dynamic['field']] === dynamic['value'] : true;

            if(!showField) return null;

            switch (type) {
                case 'text':
                    return (
                        <div key={name}>
                            <label htmlFor={name}>{title}</label>
                            <input type="text" name={name} id={name} ref={register(validationProps)} />
                            {errors[name] && <span className="red-text">{errors[name]['message']}</span>}
                        </div>
                    )
                case 'email':
                    return (
                        <div key={name}>
                            <label htmlFor={name}>{title}</label>
                            <input type="email" name={name} id={name} ref={register(validationProps)} />
                            {errors[name] && <span className="red-text">{errors[name]['message']}</span>}
                        </div>
                    )
                case 'checkbox':
                    return (
                        <div key={name}>
                            <label>
                                <input type="checkbox" name={name} id={name} ref={register(validationProps)} />
                                <span>{title}</span>
                                {errors[name] && <span className="red-text">{errors[name]['message']}</span>}
                            </label>
                        </div>
                    )
                case 'url':
                    return (
                        <div key={name}>
                            <label htmlFor={name}>{title}</label>
                            <input type="url" name={name} id={name} ref={register(validationProps)} />
                            {errors[name] && <span className="red-text">{errors[name]['message']}</span>}
                        </div>
                    )
                default:
                    return (
                        <div key={name}>
                            <span className="red-text">Invalid Field</span>
                        </div>
                    )
            }


        })
    }

    return (
        <div>
            <form onSubmit={handleSubmit(onSubmit)}>
                <h4>{title}</h4>
                {renderFields(fields)}
                <br />
                <button type="submit" className="btn">Submit</button>
            </form>
        </div>
    );
}
Example #13
Source File: LoginForm.js    From e-Pola with MIT License 5 votes vote down vote up
function LoginForm({ onSubmit }) {
  const classes = useStyles()
  const {
    register,
    handleSubmit,
    errors,
    formState: { isSubmitting, isValid }
  } = useForm({
    mode: 'onChange',
    nativeValidation: false
  })

  return (
    <form className={classes.root} onSubmit={handleSubmit(onSubmit)}>
      <TextField
        type="email"
        varient="outlined"
        name="email"
        label={<Trans>Your email here...</Trans>}
        margin="normal"
        fullWidth
        inputRef={register({
          required: true,
          validate: validateEmail
        })}
        error={!!errors.email}
        helperText={errors.email && <Trans>Email must be valid</Trans>}
      />
      <TextField
        type="password"
        varient="outlined"
        name="password"
        label={<Trans>Your password here...</Trans>}
        margin="normal"
        fullWidth
        inputRef={register({
          required: true
        })}
        error={!!errors.password}
        helperText={errors.password && <Trans>Password is required</Trans>}
      />
      <div className={classes.submit}>
        <Button
          color="primary"
          type="submit"
          variant="contained"
          disabled={isSubmitting || !isValid}>
          {isSubmitting ? <Trans>Loading</Trans> : <Trans>Login</Trans>}
        </Button>
      </div>
    </form>
  )
}
Example #14
Source File: ForgotPassword.jsx    From saasgear with MIT License 5 votes vote down vote up
function ForgotPassword() {
  useDocumentHeader({ title: 'Forgot password' });

  const [isSubmitted, setIsSubmitted] = useState(false);
  const { register, handleSubmit, errors } = useForm({
    resolver: yupResolver(ForgotPasswordSchema),
  });
  const [forgotPasswordMutation, { loading, error }] = useMutation(
    forgotpasswordQuery,
  );

  async function onSubmit(data) {
    setIsSubmitted(false);
    try {
      await forgotPasswordMutation({ variables: data });
      setIsSubmitted(true);
    } catch (e) {
      console.log(e);
      setIsSubmitted(false);
    }
  }

  return (
    <ForgotPasswordWrapper>
      <Overlay />
      <ForgotPasswordContainer>
        <ForgotPasswordForm
          onSubmit={handleSubmit(onSubmit)}
          register={register}
          errors={errors}
          isSubmitted={isSubmitted && !error}
          isSubmitting={loading}
          apiError={error?.message}
        />
        <SquareIconTop>
          <img src={squareRadiusTop} alt="" />
        </SquareIconTop>
        <SmallSquareBottom>
          <img src={squareRadiusTopPrimary} alt="" />
        </SmallSquareBottom>
        <SmallSquareTop>
          <img src={squareRadiusTopPrimarySmall} alt="" />
        </SmallSquareTop>
        <SmallSquareGrid>
          <img src={squareGrid} alt="" />
        </SmallSquareGrid>
        <SquareIconBottom>
          <img src={squareRadiusTopBig} alt="" />
        </SquareIconBottom>
        <CircleIcon>
          <img src={circleSmall} alt="" />
        </CircleIcon>
      </ForgotPasswordContainer>
    </ForgotPasswordWrapper>
  );
}
Example #15
Source File: footerform.js    From linkin with MIT License 5 votes vote down vote up
FontForm = ({ data, update, loading }) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({ defaultValues: data });

  // console.log(data);

  return (
    <>
      <div className={styles.Wrapper}>
        <div
          className={`${styles.Inner} col-10 col-sm-10 col-md-10 col-lg-10 col-xl-8 col-xxl-8 `}
        >
          <form onSubmit={(e) => e.preventDefault()}>
            <h3>Footer Details</h3>
            <div className="form-check form-switch d-grid gap-2 d-md-flex justify-content-md-end">
              <input
                className="form-check-input"
                type="checkbox"
                {...register(`footerEnabled`)}
              />
            </div>
            <div className="mb-3 ">
              <label className="form-label">Footer Font Size</label>
              <div className="input-group mb-3">
                <input
                  type="number"
                  className={
                    errors.footerTextSize
                      ? "form-control is-invalid"
                      : "form-control"
                  }
                  placeholder="Enter handler font size"
                  {...register("footerTextSize", {
                    min: { message: "Font Size must be above 1px", value: 1 },
                  })}
                />{" "}
                <span className="input-group-text">px</span>
              </div>
              {errors.footerTextSize && (
                <div className="invalid-feedback">
                  {errors.footerTextSize.message}
                </div>
              )}
            </div>
            <div className="mb-3 ">
              <label className="form-label">Footer text</label>
              <input
                type="text"
                className={
                  errors.footerText ? "form-control is-invalid" : "form-control"
                }
                placeholder="Enter Footer text"
                {...register("footerText")}
              />
            </div>
            <button
              type="submit"
              className="btn btn-primary btn-block"
              onClick={handleSubmit(update)}
              disabled={loading}
            >
              {loading && (
                <span
                  className="spinner-border spinner-border-sm me-1"
                  role="status"
                  aria-hidden="true"
                ></span>
              )}
              Save
            </button>
          </form>
        </div>
      </div>
    </>
  );
}
Example #16
Source File: Form.jsx    From sitepoint-books-firebase with MIT License 5 votes vote down vote up
function AuthorForm({ values, submit }) {
  const [errorMsg, setErrorMsg] = useState('')

  const {
    register,
    reset,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  })

  useEffect(() => {
    reset(values)
  }, [values])

  const onSubmit = (submittedData) => {
    try {
      submit(submittedData) // submit data to action handler
    } catch (err) {
      setErrorMsg(err.message)
    }
  }
  return (
    <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
      <form className="space-y-6" onSubmit={handleSubmit(onSubmit)}>
        {errorMsg && <Alert type="error" message={errorMsg} />}

        <div className="form-control">
          <label className="label" htmlFor="name">
            <span className="label-text">Name</span>
          </label>
          <input
            type="text"
            autoComplete="off"
            {...register('name')}
            className={`input input-bordered ${errors.name && 'input-error'}`}
          />
          {errors.name && (
            <span className="mt-1 text-xs text-error">
              {errors.name.message}
            </span>
          )}
        </div>

        <div className="flex justify-end space-x-4">
          <button type="submit" className="btn btn-primary btn-sm w-24">
            Save
          </button>
          <Link to="/author" className="btn btn-outline btn-sm w-24">
            Cancel
          </Link>
        </div>
      </form>
    </div>
  )
}
Example #17
Source File: login.jsx    From next-js-11-basic-authentication-example with MIT License 5 votes vote down vote up
function Login() {
    const router = useRouter();

    useEffect(() => {
        // redirect to home if already logged in
        if (userService.userValue) {
            router.push('/');
        }

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // form validation rules 
    const validationSchema = Yup.object().shape({
        username: Yup.string().required('Username is required'),
        password: Yup.string().required('Password is required')
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, setError, formState } = useForm(formOptions);
    const { errors } = formState;

    function onSubmit({ username, password }) {
        return userService.login(username, password)
            .then(() => {
                // get return url from query parameters or default to '/'
                const returnUrl = router.query.returnUrl || '/';
                router.push(returnUrl);
            })
            .catch(error => {
                setError('apiError', { message: error });
            });
    }

    return (
        <div className="col-md-6 offset-md-3 mt-5">
            <div className="alert alert-info">
                Username: test<br />
                Password: test
            </div>
            <div className="card">
                <h4 className="card-header">Next.js Basic Authentication Example</h4>
                <div className="card-body">
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <div className="form-group">
                            <label>Username</label>
                            <input name="username" type="text" {...register('username')} className={`form-control ${errors.username ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.username?.message}</div>
                        </div>
                        <div className="form-group">
                            <label>Password</label>
                            <input name="password" type="password" {...register('password')} className={`form-control ${errors.password ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.password?.message}</div>
                        </div>
                        <button disabled={formState.isSubmitting} className="btn btn-primary">
                            {formState.isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
                            Login
                        </button>
                        {errors.apiError &&
                            <div className="alert alert-danger mt-3 mb-0">{errors.apiError?.message}</div>
                        }
                    </form>
                </div>
            </div>
        </div>
    );
}
Example #18
Source File: login.jsx    From next-js-11-jwt-authentication-example with MIT License 5 votes vote down vote up
function Login() {
    const router = useRouter();

    useEffect(() => {
        // redirect to home if already logged in
        if (userService.userValue) {
            router.push('/');
        }
    }, []);

    // form validation rules 
    const validationSchema = Yup.object().shape({
        username: Yup.string().required('Username is required'),
        password: Yup.string().required('Password is required')
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, setError, formState } = useForm(formOptions);
    const { errors } = formState;

    function onSubmit({ username, password }) {
        return userService.login(username, password)
            .then(() => {
                // get return url from query parameters or default to '/'
                const returnUrl = router.query.returnUrl || '/';
                router.push(returnUrl);
            })
            .catch(error => {
                setError('apiError', { message: error });
            });
    }

    return (
        <div className="col-md-6 offset-md-3 mt-5">
            <div className="alert alert-info">
                Username: test<br />
                Password: test
            </div>
            <div className="card">
                <h4 className="card-header">Next.js JWT Login Example</h4>
                <div className="card-body">
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <div className="form-group">
                            <label>Username</label>
                            <input name="username" type="text" {...register('username')} className={`form-control ${errors.username ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.username?.message}</div>
                        </div>
                        <div className="form-group">
                            <label>Password</label>
                            <input name="password" type="password" {...register('password')} className={`form-control ${errors.password ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.password?.message}</div>
                        </div>
                        <button disabled={formState.isSubmitting} className="btn btn-primary">
                            {formState.isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
                            Login
                        </button>
                        {errors.apiError &&
                            <div className="alert alert-danger mt-3 mb-0">{errors.apiError?.message}</div>
                        }
                    </form>
                </div>
            </div>
        </div>
    );
}
Example #19
Source File: login.jsx    From next-js-11-registration-login-example with MIT License 5 votes vote down vote up
function Login() {
    const router = useRouter();

    // form validation rules 
    const validationSchema = Yup.object().shape({
        username: Yup.string().required('Username is required'),
        password: Yup.string().required('Password is required')
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, formState } = useForm(formOptions);
    const { errors } = formState;

    function onSubmit({ username, password }) {
        return userService.login(username, password)
            .then(() => {
                // get return url from query parameters or default to '/'
                const returnUrl = router.query.returnUrl || '/';
                router.push(returnUrl);
            })
            .catch(alertService.error);
    }

    return (
        <Layout>
            <div className="card">
                <h4 className="card-header">Login</h4>
                <div className="card-body">
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <div className="form-group">
                            <label>Username</label>
                            <input name="username" type="text" {...register('username')} className={`form-control ${errors.username ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.username?.message}</div>
                        </div>
                        <div className="form-group">
                            <label>Password</label>
                            <input name="password" type="password" {...register('password')} className={`form-control ${errors.password ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.password?.message}</div>
                        </div>
                        <button disabled={formState.isSubmitting} className="btn btn-primary">
                            {formState.isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
                            Login
                        </button>
                        <Link href="/account/register" className="btn btn-link">Register</Link>
                    </form>
                </div>
            </div>
        </Layout>
    );
}
Example #20
Source File: EditAccount.jsx    From react-facebook-login-example with MIT License 5 votes vote down vote up
function EditAccount({ history, match }) {
    const { id } = match.params;

    // functions to build form returned by useForm() hook
    const { register, handleSubmit, setValue, formState } = useForm();

    // pre-populate form with account details when component loads
    const [account, setAccount] = useState(null);
    useEffect(() => {
        accountService.getById(id).then(account => {
            setAccount(account);
            const fields = ['name', 'extraInfo'];
            fields.forEach(field => setValue(field, account[field]));
        });
    }, [id, setValue]);

    // form submit handler
    const [error, setError] = useState('');
    function onSubmit(data) {
        return accountService.update(id, data)
            .then(() => history.push('..'))
            .catch(err => setError(err));
    }

    return (
        <div>
            <h2>Edit Account</h2>
            <p>Updating the information here will only change it inside this application, it won't (and can't) change anything in the associated Facebook account.</p>
            {account &&
                <form onSubmit={handleSubmit(onSubmit)}>
                    <div className="form-group">
                        <label>Facebook Id</label>
                        <div>{account.facebookId}</div>
                    </div>
                    <div className="form-group">
                        <label>Name</label>
                        <input name="name" type="text" ref={register} className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>Extra Info</label>
                        <input name="extraInfo" type="text" ref={register} className="form-control" />
                    </div>
                    <div className="form-group">
                        <button type="submit" disabled={formState.isSubmitting} className="btn btn-primary">
                            {formState.isSubmitting &&
                                <span className="spinner-border spinner-border-sm mr-1"></span>
                            }
                            Save
                        </button>
                        <Link to=".." className="btn btn-link">Cancel</Link>
                        {error &&
                            <div className="alert alert-danger mt-3 mb-0">{error}</div>
                        }
                    </div>
                </form>
            }
            {!account &&
                <div className="text-center p-3">
                    <span className="spinner-border spinner-border-lg align-center"></span>
                </div>
            }
        </div>
    );
}
Example #21
Source File: Login.jsx    From react-recoil-jwt-authentication-example with MIT License 5 votes vote down vote up
function Login({ history }) {
    const auth = useRecoilValue(authAtom);
    const userActions = useUserActions();

    useEffect(() => {
        // redirect to home if already logged in
        if (auth) history.push('/');

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // form validation rules 
    const validationSchema = Yup.object().shape({
        username: Yup.string().required('Username is required'),
        password: Yup.string().required('Password is required')
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, setError, formState } = useForm(formOptions);
    const { errors, isSubmitting } = formState;

    function onSubmit({ username, password }) {
        return userActions.login(username, password)
            .catch(error => {
                setError('apiError', { message: error });
            });
    }

    return (
        <div className="col-md-6 offset-md-3 mt-5">
            <div className="alert alert-info">
                Username: test<br />
                Password: test
            </div>
            <div className="card">
                <h4 className="card-header">Login</h4>
                <div className="card-body">
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <div className="form-group">
                            <label>Username</label>
                            <input name="username" type="text" {...register('username')} className={`form-control ${errors.username ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.username?.message}</div>
                        </div>
                        <div className="form-group">
                            <label>Password</label>
                            <input name="password" type="password" {...register('password')} className={`form-control ${errors.password ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.password?.message}</div>
                        </div>
                        <button disabled={isSubmitting} className="btn btn-primary">
                            {isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
                            Login
                        </button>
                        {errors.apiError &&
                            <div className="alert alert-danger mt-3 mb-0">{errors.apiError?.message}</div>
                        }
                    </form>
                </div>
            </div>
        </div>
    )
}
Example #22
Source File: UpdateContact.js    From resume-builder with MIT License 5 votes vote down vote up
function UpdateContact() {

    const { resume, updateContact } = useContext(DetailsContext);
    const { register, handleSubmit } = useForm();

    const onSubmit = (data) => {
        updateContact(data) 
    };


    return (
        <div className="updateContact">
            <h1>Contact Details</h1>

            <div className="contactFormContainer">
                <form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)} className="contactForm">
                    <div className="contactFormOne">
                        <label className="contactLabelPhone">Phone</label>
                        <input 
                            type="text" 
                            placeholder="Eg. +91 9845361309" 
                            {...register("phone")} 
                            name="phone"
                            onChange={handleSubmit(onSubmit)}
                            className="input_c"
                            defaultValue={resume.contact.phone}
                        />
                    </div>
                    <div className="contactFormOne">
                        <label className="contactLabelEmail">Email</label>
                        <input 
                            type="text" 
                            placeholder="Eg. [email protected]" 
                            {...register("email")} 
                            name="email"
                            onChange={handleSubmit(onSubmit)}
                            className="input_c"
                            defaultValue={resume.contact.email}
                        />
                    </div>
                    <div className="contactFormThree">
                        <label className="contactLabelWebsite">Website</label>
                        <input 
                            type="text" 
                            placeholder="Eg. www.myofficialsite.com" 
                            {...register("website")} 
                            name="website"
                            onChange={handleSubmit(onSubmit)}
                            className="input_c"
                            defaultValue={resume.contact.website}
                        />
                    </div>
                    <div className="contactFormFour">
                        <label className="contactLabelAddress">Address</label>
                        <textarea 
                            type="text" 
                            placeholder="Eg. 123 Main Street, New York, NY 10030" 
                            {...register("address")} 
                            name="address"
                            onChange={handleSubmit(onSubmit)}
                            className="input_add"
                            defaultValue={resume.contact.address}
                        />
                    </div>

                    <Button type="submit" onClick={handleSubmit(onSubmit)}>Save</Button>
                </form>
            </div>
        </div>
    )
}
Example #23
Source File: Form.js    From react-native-expo-starter-kit with MIT License 5 votes vote down vote up
ArticlesForm = ({
  error, loading, success, onFormSubmit, defaultValues,
}) => {
  const {
    register, handleSubmit, errors, setValue,
  } = useForm({ defaultValues });

  useEffect(() => {
    register({ name: 'email' }, { required: errorMessages.missingEmail });
  }, [register]);

  return (
    <Container>
      <Content padder>
        <Header
          title="Example form"
          content="When you submit the form, it'll simply save to your redux store"
        />

        {error && <Messages message={error} />}
        {loading && <Messages type="info" message="Loading..." />}
        {success && <Messages type="success" message={success} />}

        <Form>
          <Item stackedLabel>
            <Label>Email*</Label>
            <Input
              type="text"
              autoCapitalize="none"
              placeholder="[email protected]"
              keyboardType="email-address"
              defaultValue={defaultValues.email || ''}
              onChangeText={(value) => setValue('email', value)}
            />
          </Item>
          {errors.email && <Text>{errors.email.message}</Text>}

          <Spacer size={20} />

          <Button block onPress={handleSubmit(onFormSubmit)} disabled={loading}>
            <Text>{loading ? 'Loading' : 'Submit'}</Text>
          </Button>
        </Form>
      </Content>
    </Container>
  );
}
Example #24
Source File: Submit.jsx    From my-fav-tubes with MIT License 5 votes vote down vote up
Submit = () => {
  const [videos, setVideos] = useState([])
  const [update, setUpdate] = useState(false)
  const { handleSubmit, register, errors } = useForm()
  const url = 'http://localhost:5555/api/videos/'
  const onSubmit = (values) => {
    console.log('values', typeof values)
    axios
      .post(url, values)
      .then((res) => {
        setVideos(res.data)
        setUpdate(!update)
      })
      .catch((err) => console.log(`Error: ${err}`))
      .finally()
  }

  useEffect(() => {
    axios
      .get(url)
      .then((res) => {
        setVideos(res.data)
      })
      .catch((err) => console.log(`Error: ${err}`))
  }, [update])
  console.log('videos', videos)

  return (
    <StyledDiv>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input
          type="text"
          placeholder="Enter your YouTube URL"
          name="url"
          ref={register({
            required: 'Required',
            pattern: {
              // value: '',
              message: 'invalid YouTube url',
            },
          })}
        />
        {errors.url && errors.url.message}
        <button type="submit">submit</button>
      </form>
      <CardList data={videos} />
    </StyledDiv>
  )
}
Example #25
Source File: NameForm.jsx    From minihackathon-2022 with MIT License 5 votes vote down vote up
function NameForm({ formKey, handleSubmitFunc, width }) {
	const {
		register,
		handleSubmit,
		formState: { errors },
	} = useForm({
		resolver: yupResolver(memberSchema),
	});

	useEffect(() => {
		handleSubmitFunc &&
			handleSubmitFunc(formKey, () => {
				return new Promise((resolve, reject) => {
					handleSubmit(
						(data) => {
							resolve(data);
						},
						() => {
							resolve(null);
						}
					)();
				});
			});
	}, []); // eslint-disable-line react-hooks/exhaustive-deps

	return (
		<div className="h-full" style={{ width: width || "20%" }}>
			<h1 className="text-xl font-bold text-center">Team details</h1>
			<label className="block font-semibold text-[#969696] text-[1em] md:text-left mb-1 md:mb-0 pr-4">
				Team Name
			</label>
			<input
				{...register("teamName")}
				type="text"
				placeholder="Team Name"
				className="border-2 border-black rounded mb-[0.1em] px-2 py-1 w-full"
			/>
			<p className="text-red-500 text-[0.8em] font-semibold min-h-[1em] italic">
				{errors.teamName?.message}
			</p>

			<label className="block font-semibold text-[#969696] text-[1em] md:text-left mb-1 md:mb-0 pr-4">
				Team Size
			</label>
			<select
				{...register("count")}
				defaultValue=""
				className="border-2 border-black rounded mb-[0.1em] py-1 px-1 cursor-pointer w-full"
			>
				<option value="0">Choose</option>
				<option value="3">3</option>
				<option value="4">4</option>
			</select>
			<p className="text-red-500 text-[0.8em] font-semibold min-h-[1em] italic">
				{errors.count?.message}
			</p>
		</div>
	);
}
Example #26
Source File: index.jsx    From stream-live-system with MIT License 5 votes vote down vote up
NewLiveModal = ({ openModal, closeModal }) => {
  const { register, handleSubmit, errors } = useForm({
    validationSchema: validationSchema,
  });

  const onSubmit = (data) => {
    Api.post('/api/lives', data)
    .then((res) => {
      redirect('/');
    });
  }

  return (
    <Modal
      isOpen={ openModal }
      onRequestClose={ closeModal }
      contentLabel="Example Modal">
      
      <form onSubmit={ handleSubmit(onSubmit) } className="form-new-live">
        <h1 className="title-modal">New live</h1>
        <div className="container-input">
          <CustomInput
            classs={ 'width-80 mt-25' }
            type={ 'text' }
            name={ 'title' }
            placeholder={ 'Title' }
            errors={ errors.title }
            register={ register }
          />

          <CustomInput
            classs={ 'width-80 mt-25' }
            type={'text'}
            name={'description'}
            placeholder={'Description'}
            errors={ errors.description }
            register={ register }
          />

          <CustomInput
            classs={ 'width-80 mt-25' }
            type={'date'}
            name={'date'}
            placeholder={''}
            errors={ errors.date }
            register={ register }
          />

          <CustomInput
            classs={ 'width-80' }
            type={'password'}
            name={'password'}
            placeholder={'Password'}
            errors={ errors.password }
            register={ register }
          />
          
          <button className="btn btn-rounded black-btn btn-outlined">Create</button>
        </div>
      </form>
    </Modal>
  )
}
Example #27
Source File: Action.jsx    From pooltogether-governance-ui with MIT License 5 votes vote down vote up
CustomAbiInput = (props) => {
  const { contract, setContract } = props

  const { t } = useTranslation()
  const abiFormName = 'contractAbi'
  const { register, watch } = useForm()
  const abiString = watch(abiFormName, false)
  const [abiError, setAbiError] = useState(false)

  useEffect(() => {
    if (abiString) {
      try {
        const abi = JSON.parse(abiString)
        setContract({
          ...contract,
          abi
        })
        setAbiError(false)
      } catch (e) {
        console.warn(e.message)
        setContract({
          ...contract,
          abi: null
        })
        setAbiError(true)
      }
    } else if (contract.abi) {
      setContract({
        ...contract,
        abi: null
      })
      setAbiError(false)
    }
  }, [abiString])

  return (
    <SimpleInput
      className='mt-4'
      label={t('contractAbi')}
      name={abiFormName}
      register={register}
      required
      placeholder='[{ type: "function", ...'
      errorMessage={abiError ? t('errorWithAbi') : ''}
    />
  )
}
Example #28
Source File: Step1.js    From ultimate-react-hook-form-form with MIT License 5 votes vote down vote up
Step1 = () => {
  const { setValues, data } = useData();
  const history = useHistory();
  const { register, handleSubmit, errors } = useForm({
    defaultValues: { firstName: data.firstName, lastName: data.lastName },
    mode: "onBlur",
    resolver: yupResolver(schema),
  });

  const onSubmit = (data) => {
    history.push("./step2");
    setValues(data);
  };

  return (
    <MainContainer>
      <Typography component="h2" variant="h5">
        ? Step 1
      </Typography>
      <Form onSubmit={handleSubmit(onSubmit)}>
        <Input
          {...register('parentName')}
          id="firstName"
          type="text"
          label="First Name"
          name="firstName"
          error={!!errors.firstName}
          helperText={errors?.firstName?.message}
        />
        <Input
          ref={register}
          id="lastName"
          type="text"
          label="Last Name"
          name="lastName"
          error={!!errors.lastName}
          helperText={errors?.lastName?.message}
        />
        <PrimaryButton>Next</PrimaryButton>
      </Form>
    </MainContainer>
  );
}
Example #29
Source File: GrantModal.js    From akashlytics-deploy with GNU General Public License v3.0 4 votes vote down vote up
GrantModal = ({ address, onClose }) => {
  const formRef = useRef();
  const [error, setError] = useState("");

  const classes = useStyles();
  const { sendTransaction } = useTransactionModal();
  const {
    handleSubmit,
    control,
    formState: { errors },
    watch,
    clearErrors
  } = useForm({
    defaultValues: {
      amount: "",
      expiration: format(addYears(new Date(), 1), "yyyy-MM-dd'T'HH:mm"),
      useDepositor: false,
      granteeAddress: ""
    }
  });
  const { amount, granteeAddress, expiration } = watch();

  const onDepositClick = (event) => {
    event.preventDefault();
    formRef.current.dispatchEvent(new Event("submit", { cancelable: true, bubbles: true }));
  };

  const onSubmit = async ({ amount }) => {
    setError("");
    clearErrors();
    const spendLimit = aktToUakt(amount);

    const expirationDate = new Date(expiration);
    const message = TransactionMessageData.getGrantMsg(address, granteeAddress, spendLimit, expirationDate);
    const response = await sendTransaction([message]);

    if (response) {
      await analytics.event("deploy", "authorize spend");

      onClose();
    }
  };

  function handleDocClick(ev, url) {
    ev.preventDefault();

    window.electron.openUrl(url);
  }

  return (
    <Dialog maxWidth="xs" aria-labelledby="deposit-dialog-title" open={true} onClose={onClose}>
      <DialogTitle id="deposit-dialog-title">Authorize Spending</DialogTitle>
      <DialogContent dividers className={classes.dialogContent}>
        <form onSubmit={handleSubmit(onSubmit)} ref={formRef}>
          <Alert severity="info">
            <Typography variant="caption">
              <LinkTo onClick={(ev) => handleDocClick(ev, "https://docs.akash.network/testnet-technical-docs/authorized-spend")}>Authorized Spend</LinkTo>{" "}
              allows users to authorize spend of a set number of tokens from a source wallet to a destination, funded wallet. The authorized spend is restricted
              to Akash deployment activities and the recipient of the tokens would not have access to those tokens for other operations.
            </Typography>
          </Alert>

          <FormControl error={!errors.amount} className={classes.formControl} fullWidth>
            <Controller
              control={control}
              name="amount"
              rules={{
                required: true
              }}
              render={({ fieldState, field }) => {
                const helperText = fieldState.error?.type === "validate" ? "Invalid amount." : "Amount is required.";

                return (
                  <TextField
                    {...field}
                    type="number"
                    variant="outlined"
                    label="Spending Limit"
                    autoFocus
                    error={!!fieldState.invalid}
                    helperText={fieldState.invalid && helperText}
                    className={classes.formValue}
                    inputProps={{ min: 0, step: 0.000001 }}
                    InputProps={{
                      startAdornment: <InputAdornment position="start">AKT</InputAdornment>
                    }}
                  />
                );
              }}
            />
          </FormControl>

          <FormControl className={classes.formControl} fullWidth>
            <Controller
              control={control}
              name="granteeAddress"
              defaultValue=""
              rules={{
                required: true
              }}
              render={({ fieldState, field }) => {
                return (
                  <TextField
                    {...field}
                    type="text"
                    variant="outlined"
                    label="Grantee Address"
                    error={!!fieldState.invalid}
                    helperText={fieldState.invalid && "Grantee address is required."}
                    className={classes.formValue}
                  />
                );
              }}
            />
          </FormControl>

          <FormControl className={classes.formControl} fullWidth>
            <Controller
              control={control}
              name="expiration"
              rules={{
                required: true
              }}
              render={({ fieldState, field }) => {
                return (
                  <TextField
                    {...field}
                    type="datetime-local"
                    variant="outlined"
                    label="Expiration"
                    error={!!fieldState.invalid}
                    helperText={fieldState.invalid && "Expiration is required."}
                    className={classes.formValue}
                  />
                );
              }}
            />
          </FormControl>

          {!!amount && granteeAddress && (
            <Box marginTop={1} textAlign={"left"}>
              This address will be able to spend up to {amount}AKT on your behalf.
            </Box>
          )}

          {error && (
            <Alert severity="warning" className={classes.alert}>
              {error}
            </Alert>
          )}
        </form>
      </DialogContent>
      <DialogActions className={classes.dialogActions}>
        <Button autoFocus onClick={onClose}>
          Cancel
        </Button>
        <Button onClick={onDepositClick} disabled={!amount} variant="contained" color="primary">
          Grant
        </Button>
      </DialogActions>
    </Dialog>
  );
}