react-hook-form#FormProvider JavaScript Examples

The following examples show how to use react-hook-form#FormProvider. 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: ConnectionFormProvider.jsx    From tinkerun with MIT License 6 votes vote down vote up
ConnectionFormProvider = ({children, defaultValues}) => {
  const methods = useForm()
  const {reset} = methods

  // 解决表单不能根据默认值重新填充的问题
  // https://github.com/react-hook-form/react-hook-form/discussions/2282#discussioncomment-39308
  useEffect(() => {
    reset(defaultValues)
  }, [defaultValues.id])

  return (
    <FormProvider {...methods}>
      {children}
    </FormProvider>
  )
}
Example #2
Source File: App.js    From hook-form-mui with MIT License 4 votes vote down vote up
function App(props) {
  const methods = useForm({
    resolver: yupResolver(validationSchema),
  });
  const { handleSubmit, errors } = methods;

  const onSubmit = (data) => {
    console.log(data);
  };

  const numberData = [
    {
      id: "10",
      label: "Ten",
    },
    {
      id: "20",
      label: "Twenty",
    },
    {
      id: "30",
      label: "Thirty",
    },
  ];

  const radioGroupOptions = [
    {
      value: "female",
      label: "Female",
    },
    {
      value: "male",
      label: "Male",
    },
    {
      value: "other",
      label: "Other",
    },
  ];

  return (
    <div style={{ padding: "10px" }}>
      <Button
        variant="contained"
        color="primary"
        onClick={handleSubmit(onSubmit)}
      >
        SUBMIT
      </Button>

      <div style={{ padding: "10px" }}>
        <FormProvider {...methods}>
          <form>
            <Grid container spacing={2}>
              <Grid item xs={6}>
                <FormInput name="name" label="Name" />
              </Grid>
              <Grid item xs={6}>
                <FormInput
                  name="nameV"
                  label="Name with Validation"
                  required={true}
                  errorobj={errors}
                />
              </Grid>
              <Grid item xs={6}>
                <FormSelect name="sel" label="Numbers" options={numberData} />
              </Grid>
              <Grid item xs={6}>
                <FormSelect
                  name="selV"
                  label="Numbers with Validation"
                  options={numberData}
                  required={true}
                  errorobj={errors}
                />
              </Grid>
              <Grid item xs={6}>
                <FormSelectAutoComplete
                  name="selAuto"
                  label="Auto Select Numbers"
                  options={numberData}
                  isMulti
                />
              </Grid>
              <Grid item xs={6}>
                <FormSelectAutoComplete
                  name="selAutoV"
                  label="Auto Select Numbers with Validation"
                  options={numberData}
                  isMulti
                  required={true}
                  errorobj={errors}
                />
              </Grid>
              <Grid item xs={6}>
                <FormDatePicker name="txtDate" label="Mui Date" />
              </Grid>
              <Grid item xs={6}>
                <FormDatePicker
                  name="txtDateV"
                  label="Mui Date Validation"
                  required={true}
                  errorobj={errors}
                />
              </Grid>
              <Grid item xs={6}>
                <FormCheckbox name="chk" label="Mui Checkbox" />
              </Grid>
              <Grid item xs={6}>
                <FormRadio
                  name="gender"
                  label="Gender"
                  options={radioGroupOptions}
                />
              </Grid>
            </Grid>
          </form>
        </FormProvider>
      </div>
    </div>
  );
}
Example #3
Source File: ProposalCreationForm.jsx    From pooltogether-governance-ui with MIT License 4 votes vote down vote up
ProposalCreationForm = () => {
  const { t } = useTranslation()
  const { refetch: refetchAllProposals } = useAllProposals()

  const { userCanCreateProposal } = useUserCanCreateProposal()
  const formMethods = useForm({
    mode: 'onSubmit',
    defaultValues: {
      title: '',
      description: '',
      actions: [EMPTY_ACTION]
    }
  })

  const [showSummary, setShowSummary] = useState(false)
  const [validFormData, setValidFormData] = useState()
  const [showModal, setShowModal] = useState(false)

  const chainId = useGovernanceChainId()
  const governanceAddress = CONTRACT_ADDRESSES[chainId]?.GovernorAlpha
  const [txId, setTxId] = useState(0)
  const sendTx = useSendTransaction(t, poolToast)
  const tx = useTransaction(txId)

  const onCancelled = () => setShowModal(false)

  const onSuccess = () => {
    refetchAllProposals()
  }

  const submitTransaction = async () => {
    const params = getProposeParamsFromForm(validFormData, t)
    if (!params) return

    const txId = await sendTx({
      name: t('propose'),
      contractAbi: GovernorAlphaABI,
      contractAddress: governanceAddress,
      method: 'propose',
      params,
      callbacks: {
        onCancelled,
        onSuccess
      }
    })
    setTxId(txId)
    setShowModal(true)
  }

  const onSubmit = async (data) => {
    window?.scrollTo(0, 0)
    setShowSummary(true)
    setValidFormData(data)
  }
  const onError = (data) => {
    const parsedErrorMessages = []

    if (data?.title?.message) parsedErrorMessages.push(data.title.message)
    if (data?.description?.message) parsedErrorMessages.push(data.description.message)

    if (data?.actions) {
      data?.actions.forEach((action) => {
        if (action?.contract?.address?.message) {
          parsedErrorMessages.push(action.contract.address.message)
        }

        if (action?.contract?.message) {
          parsedErrorMessages.push(action.contract.message)
        }

        if (action?.contract?.fn?.message) {
          parsedErrorMessages.push(action.contract.fn.message)
        }

        if (action?.contract?.fn?.payableAmount?.message) {
          parsedErrorMessages.push(action.contract.fn.payableAmount.message)
        }

        if (action?.contract?.fn?.values) {
          Object.keys(action.contract.fn.values).forEach((fnName) => {
            if (action.contract.fn.values[fnName]?.message) {
              parsedErrorMessages.push(action.contract.fn.values[fnName].message)
            }
          })
        }
      })
    }

    poolToast.error(parsedErrorMessages.join('. '))
  }

  const closeModal = () => {
    setShowModal(false)
    setShowSummary(false)
  }

  return (
    <>
      <ProposalTransactionModal
        tx={tx}
        isOpen={showModal}
        closeModal={closeModal}
        resetForm={formMethods.reset}
      />
      <FormProvider {...formMethods}>
        <form onSubmit={formMethods.handleSubmit(onSubmit, onError)}>
          <div className={classnames('flex flex-col', { hidden: showSummary })}>
            <ActionsCard />
            <TitleCard />
            <DescriptionCard />
            {!userCanCreateProposal && <ProposalCreationWarning />}
            <Button className='mb-16 w-full' disabled={!userCanCreateProposal} type='submit'>
              {t('previewProposal')}
            </Button>
          </div>

          {showSummary && (
            <ProposalSummary
              submitTransaction={submitTransaction}
              showForm={() => {
                setShowSummary(false)
                window.scrollTo(0, 0)
              }}
              getValues={formMethods.getValues}
              handleSubmit={formMethods.handleSubmit}
            />
          )}
        </form>
      </FormProvider>
    </>
  )
}