๐Ÿ“‹ React Hooks for forms validation (Web + React Native)

Overview

Performant, flexible and extensible forms with easy to use validation.

npm downloads npm npm Discord

English | ็นไธญ | ็ฎ€ไธญ | ๆ—ฅๆœฌ่ชž | ํ•œ๊ตญ์–ด | Franรงais | Italiano | Portuguรชs | Espaรฑol | ะ ัƒััะบะธะน | Deutsch | Tรผrkรงe

Features

Install

npm install react-hook-form

Links

Quickstart

import React from 'react';
import { useForm } from 'react-hook-form';

function App() {
  const { register, handleSubmit, errors } = useForm(); // initialize the hook
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstname" ref={register} /> {/* register an input */}
      <input name="lastname" ref={register({ required: true })} />
      {errors.lastname && 'Last name is required.'}
      <input name="age" ref={register({ pattern: /\d+/ })} />
      {errors.age && 'Please enter number for age.'}
      <input type="submit" />
    </form>
  );
}

Sponsors

Thanks go to these kind and lovely sponsors (company and individuals)!

@sayav @lemcii @washingtonsoares @lixunn @SamSamskies @peaonunes @wilhelmeek @iwarner @joejknowles @chris-gunawardena @Tymek @Luchanso @vcarel @gragland @tjshipe @krnlde @msutkowski @mlukaszczyk

Backers

Thanks go to all our backers! [Become a backer].

Organizations

Thanks go to these wonderful organizations! [Contribute].

Contributors

Thanks go to these wonderful people! [Become a contributor].

Comments
  • #1580 Controller with render props API

    #1580 Controller with render props API

    ๐Ÿ”Origin

    This PR is led by a TS bug #1580 where required props will require to fulfill again at the props.

    Example CSB: https://codesandbox.io/s/react-hook-form-controller-template-qrtco

    type MyInputProps = {
      value: any;
      onChange: () => void;
    };
    
    function MyInput(props: MyInputProps) {
      return <input name="FirstName" {...props} />;
    }
    
    <Controller
      as={<input name="FirstName" />} // result in TS error for required onChange and value 
      defaultValue="FirstName"
      control={control}
    />
    

    โœ๏ธSolutions

    Render prop was purposed by @kotarella1110 which also lead to a discussion around shaping better API. Here are the options


    OPTION A only support Render Props for Controller

    cons:

    1. verbose for simple usage
    2. impact API consistency between ErrorMessage and Controller

    pros:

    1. consistent usage with Controller
    2. less code inside lib
    3. predictable result

    OPTION B support both as and render

    cons:

    1. less intuitive consider providing two options: as vs render. this could lead to confusion.
    2. lack of consistent usage

    pros:

    1. consistent API across ErrorMessage & Controller
    2. more code inside lib
    3. simple usage option, plug-in & play
    4. the community seems to be keener with both options

    โŒ OPTION C render support render props and component

    This approach having issues with good/easy TS support and having issue useFieldArray (which lead input to remount)

    Screen Recording 2020-05-30 at 10 46 28 am


    ๐Ÿ“งPoll result

    The above options lead us into discussion and poll on twitter. Below is a good result.

    image


    ๐Ÿ“ฆWhat's next?

    The plan is to release an RC.2 version with option B and waiting for the community's feedback for 2 weeks before releasing the new V6. During the period, if users raise concerns over the new API and we will re-look at option A again.


    ๐Ÿ“˜Changes

    • [x] Controller

    Less of a breaking change for existing users, simple usage remain while still give the user the full control with render prop. Remove the following props

    • onChange
    • onChangeName
    • onBlur
    • onBlurName
    • valueName

    Simple usage as below, will not be impacted:

    <Controller as={TextField} control={control} name="test" />
    

    Usage involed configration and those remmoved props:

    -<Controller 
    -  as={CustomInput} 
    -  valueName="textValue"
    -  onChangeName="onTextChange"
    -  control={control} 
    -  name="test"  
    -/>
    +<Controller 
    +  render={({ onChange, onBlur, value }) => (
    +     <CustomInput onTextChange={onChange} onBlur={onBlur} textValue={value} />
    +  )}
    +  control={control} 
    +  name="test"  
    +/>
    

    • [x] ErrorMessage

    change render props from children to render, usage change from the ability to use both to either. you can either use as or render. for multiple error messages, you will have to use render

    <ErrrorMessage errors={errors} as="p" />
    <ErrrorMessage errors={errors} render={({message}) => {message}} />
    

    Note: Both ErrorMessage and Controller contains as and render props. Users should either use as or render.

    โŒ<Controller as={TextField}  render={(props) => <TextField {...props} />}/>
    โŒ<ErrorMessage as={TextField}  render={({ message }) => {message} }/>
    
    โœ…<Controller as={TextField}  />
    โœ…<Controller render={(props) => <TextField {...props} />}/>
    
    โœ…<ErrorMessage as={TextField} />
    โœ…<ErrorMessage render={({ message }) => {message} }/>
    
    opened by bluebill1049 111
  • [Bug]: Regression: TS2589: Type instantiation is excessively deep and possibly infinite

    [Bug]: Regression: TS2589: Type instantiation is excessively deep and possibly infinite

    Version Number

    7.16.2

    Codesandbox/Expo snack

    Codesandbox still doesn't allow me to install the latest version

    Steps to reproduce

    1. Upgrade from 7.16.1 to 7.16.2, no other changes
    2. Cue error

    Expected behaviour

    TypeScript compilation should succeed without any warnings. I believe #6658 is the cause of introducing this error, this is a regression of #4441

    What browsers are you seeing the problem on?

    No response

    Relevant log output

    No response

    Code of Conduct

    • [X] I agree to follow this project's Code of Conduct
    TS 
    opened by StampixSMO 64
  • ๐Ÿ’ˆ useFieldArray

    ๐Ÿ’ˆ useFieldArray

    New custom hook for FieldArray:

    โœจ useFieldArray

    https://codesandbox.io/s/react-hook-form-usefieldarray-vy8fv

      const { fields, append, prepend, remove, move, swap, insert } = useFieldArray({
        control, // optional
        name: "test"
      });
    

    latest beta version: 4.5.0-beta.2

    • [x] building the hook
    • [x] unit test
    • [x] automation
      • normal flow
      • with default values
    • [x] website documenation
    opened by bluebill1049 64
  • RFC: async defaultValues

    RFC: async defaultValues

    Summary

    The current status of setting defaultValues from async data source is using reset:

    useEffect(() => {
      reset({
         firstName: 'test',
      })
    });
    

    honestly, this is probably not a pretty and clean approach... a few weeks before we had a feature request regarding async defaultValues: https://github.com/react-hook-form/react-hook-form/issues/2335

    Proposal Solutions

    1. defaultValues accept Promise, and promise will get resolve after useEffect, although I do have concern over the confusion which prop support both object and Promise.
    const { formState: { isLoading } } = useForm({
      defaultValues: async () => ({ firstName: 'test' })
      // defaultValues: new Promise()
    }, [])
    

    happy to discuss more options on the table too.

    feature request 
    opened by bluebill1049 58
  • Remove Dirty Prop

    Remove Dirty Prop

    I would like to be able to disable the dirty prop as it is causing unnecessary re renders of components, this is happening when the dirty prop is toggling, I would like to be able to override this by passing a prop of dirtyDisable to useForm which will make the dirty prop either always true or just remove it from the useForm return all together.

    wont be worked on 
    opened by The-Code-Monkey 57
  • Custom yup validation with useFieldArray doesn't always trigger re-render

    Custom yup validation with useFieldArray doesn't always trigger re-render

    Describe the bug I have custom yup validation which checks if there are same names in field array and returns false if there are 2 or more items with the same name. This works fine if you add 2 items to field array. When you add third one, validation is always "1 step behind" after rendering. It is validated, but render is not triggered so the error css is not displayed for the last field that is invalid.

    To Reproduce Steps to reproduce the behavior:

    1. Go to sandbox link
    2. Click on "+ Custom job" button at the top of the page, new job is added
    3. Click on "+ Custom job" button at the top of the page, new job is added and validation occurred, both new jobs with empty names are marked with red border to indicate error
    4. Click on "+ Custom job" button at the top of the page, third new job is added, but validation didn't trigger re-render and last invalid custom job doesn't have red border. This pattern happens each time with any dynamically added custom job, but only for third added item. If you add more, always the last one is not marked as invalid. There is also log in the console when validation occurs and when rendering occurs.

    Codesandbox link https://codesandbox.io/s/react-hook-form-usefieldarray-owyo0?file=/src/index.js

    Expected behavior All new custom jobs with empty names should be marked red, re-render should be triggered after each validation.

    question 
    opened by rvision 56
  • Field arrays lose their focus or position when reset

    Field arrays lose their focus or position when reset

    Describe the bug As part of our auto-save mechanism, we reset the form before save so that the default values will be set properly for the next auto save.

    The auto save, and therefore the reset, happen on a timer, which means that the user may have a field focused when the save happens.

    If the field they have focused is in a field array, then the documented method of using the field id as key causes the entire array item field to rerender because the id is recreated upon reset.

    We're using stable keys to work around this, but that may be a bug.

    Even with this, if the user has a text input focused when a reset happens and their cursor is somewhere other than the beginning of the field, the cursor will jump to the beginning of the text input. This is not the case for normal inputs, only for field arrays.

    The reason appears to be that field arrays actually modify the value attribute of the element, which is different than regular fields. I can reproduce this by modifying value on a timer without involving react hook form.

    To Reproduce Steps to reproduce the behavior:

    1. Go to https://codesandbox.io/s/react-hook-form-usefieldarray-template-forked-ht83m?file=/src/index.js
    2. Click on the first name field and replace the text with "Test"
    3. Click "RESET DELAY" and then quickly click on the first name field, positioning your cursor at the end of the word "Test"
    4. Wait for the timeout and observe that the cursor jumps to the beginning of the field

    Codesandbox link (Required) https://codesandbox.io/s/react-hook-form-usefieldarray-template-forked-ht83m?file=/src/index.js

    Expected behavior I'd expect the value attribute to not change so that the cursor does not jump. I'd also expect that the field id does not change on reset so it could be used as a stable key, or for the documentation to be updated accordingly.

    Thanks!

    enhancement 
    opened by aaronjensen 52
  • IE11 support ?

    IE11 support ?

    Hi,

    Thanks for the great library. I've been using it for all my projects, but it does not work on IE11. Can you add support for this one ?

    I got Syntax error in useForm/index.es.js (line 9)

    If you have IE11, you can try it here https://comptaplan-dev.netlify.com

    Thank you

    question 
    opened by opeah 50
  • isValid is sometimes false despite no errors

    isValid is sometimes false despite no errors

    Describe the bug I sometimes get isValid = false despite having no visible errors and errors object being an empty object ({})

    To Reproduce I do not yet have a reproducable sandbox, but I already found a code piece that might be the problem. Please see additional context

    Expected behavior isValid should always reflect what the errors object contains (e.g. isValid = Object.keys(errors).length === 0)

    Desktop (please complete the following information):

    • OS: Windows 10 202001
    • Browser: Microsoft Edge
    • Version: 86.0.621.0 (Official build) canary (64-bit)

    Additional context The problematic line could be this code piece here: https://github.com/react-hook-form/react-hook-form/blob/03216edb0b29bae631fb752e6ec612111d82798d/src/useForm.ts#L341 which triggers revalidation but without providing an isValid parameter as the 4th parameter. Hence this line https://github.com/react-hook-form/react-hook-form/blob/03216edb0b29bae631fb752e6ec612111d82798d/src/useForm.ts#L218 will resolve in !!isValid which essentially means !!undefined === false.

    AFAIK the problem only appears on async filled inputs (inputs that get their value via an api request).

    opened by krnlde 49
  • useWatch within a nested useFieldArray removing a item just before another causes useWatch go out of sync

    useWatch within a nested useFieldArray removing a item just before another causes useWatch go out of sync

    Describe the bug When using useWatch within a nested useFieldArray removing a item just before another causes useWatch go out of sync. For the item its assigned to it does not pick up the changes, however it seems to take those of the next added item.

    To Reproduce

    1. Create a form with a nested useFieldArray
    2. Append 2 elements to list
    3. Remove the first and type - noticing that the watched prop is not changing
    4. Add a element and something in the second item - noticing that both the first and second items watch component seem to be updating

    Codesandbox link (Required) https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-t29u3?file=/src/nestedFieldArray.js

    Expected behavior useWatch returns the value of the index/item its assigned too

    Desktop (please complete the following information):

    OS: Mac (Mojave 10.14.6) Browser: Chrome Version: 84

    enhancement 
    opened by meman 49
  • Material UI + multiple checkboxes + default selected

    Material UI + multiple checkboxes + default selected

    I am trying to build a form which accommodates multiple 'grouped' checkboxes using Material UI.

    The checkboxes are created async from a HTTP Request.

    I want to provide an array of the objects IDs as the default values:

    defaultValues: { boat_ids: trip?.boats.map(boat => boat.id.toString()) || [] },

    Also, when I select or deselect a checkbox, I want to add/remove the ID of the object to the values of react-hook-form.

    How can I achieve that?

    Here is a sample that I am trying to reproduce the issue:

    https://codesandbox.io/s/smoosh-dream-zmszs?file=/src/App.js

    Right now with what I have tried, I get this:

    Screenshot 2020-04-28 at 03 10 04

    Bonus point, validation of minimum selected checkboxes using Yup

    boat_ids: Yup.array() .min(2, ""),

    Thanks in advance!

    question 
    opened by mKontakis 48
  • ๐Ÿ–จ close #9058 avoid clone object when contains prototype methods

    ๐Ÿ–จ close #9058 avoid clone object when contains prototype methods

    thanks go to @kaisermann's feedback and proposal and this package ๐Ÿ™ https://github.com/jonschlinkert/is-plain-object.

    ref: https://codesandbox.io/s/throbbing-leaf-ojyutz?file=/src/App.tsx

    • [ ] update doc
    • [x] update test
    • [x] pre release

    related issue: #9058 original RFC: https://github.com/react-hook-form/react-hook-form/discussions/8030#discussioncomment-3707166

    opened by bluebill1049 3
  • ๐Ÿ“ฝ feature: `validate` function to include formValues

    ๐Ÿ“ฝ feature: `validate` function to include formValues

    Benefits

    • include formValues as part of validating function payload
    • this also improves the capability by exporting validation function external without extra function dependency

    Example

    CSB: https://codesandbox.io/s/pedantic-babycat-cj3q8r?file=/src/App.tsx

    register('test', {
      validate: (value: string, formValues: FormValues) => {
        return formValues.data == value;
      }
    })
    

    Full Example

    type FormValues = {
      number1: number;
      number2: number;
    };
    
    function validateNumber(_: number, formValus: FormValues) {
      return formValus.number1 + formValus.number2 === 3;
    }
    
    export default function App() {
      const {
        register,
        handleSubmit,
        formState: { isValid }
      } = useForm({
        mode: "onChange",
        defaultValues: {
          number1: 0,
          number2: 0
        }
      });
    
      return (
        <div>
          <form onSubmit={handleSubmit((data) => console.log(data))}>
            <input
              type="number"
              {...register("number1", {
                validate: validateNumber,
                valueAsNumber: true
              })}
              placeholder="Number1"
            />
            <input
              type="number"
              {...register("number2", {
                validate: validateNumber,
                valueAsNumber: true
              })}
              placeholder="Number2"
            />
            <p>{isValid ? "yes" : "no"}</p>
            <input type="submit" />
          </form>
        </div>
      );
    }
    
    opened by bluebill1049 2
  • ๐Ÿงช POC: support async defaultValues

    ๐Ÿงช POC: support async defaultValues

    RFC: https://github.com/react-hook-form/react-hook-form/discussions/9046

    Proposal Syntax

    The following syntax will support async defaultValues, so we will manage the reset form internally and update isLoading formState accordingly.

    const fetchFormValues = () => {
      const values = fetch('API')
    
      return {
        values,
        resetOptions: {
           keepDirtyValues: true,
        }
      }
    }
    
    const { formState: { isLoading } } = useForm({
      defaultValues: fetchFormValues
    })
    
    // you can display a loading content or disable the form for better UX
    if (isLoading) {
      return <div>Loading...</div>;
    }
    
    return <form />
    
    opened by bluebill1049 2
  • Forward custom props from Controller to render

    Forward custom props from Controller to render

    I have this situation where I need to wrap inputs inside a Controller depending on any parent prop Eg:

    export function Foo({error}) {
      {/* ... */}
      const WrappedComponent = ({ field }) => {
        return (
          <TextField
            error={error}
            {/* ... */}
          />
        );
      };
    
      return (
        <Controller
          name="firstName"
          control={control}
          render={WrappedComponent}
        />
      );
    }
    

    And creating components inside components without memoization leads to the nested component and all its children being recreated during each re-render. A property to pass down custom properties could prevent this behavior

    something like this:

    const WrappedComponent = ({ field, customProps }) => {
      return (
        <TextField
          error={customProps.error}
          {/* ... */}
        />
      );
    };
    
    export function Foo({error}) {
      ...
      return (
        <Controller
          name="firstName"
          control={control}
          render={WrappedComponent}
          customProps={{ error }}
        />
      );
    }
    
    opened by NetoBraghetto 3
  • Bump vite from 2.9.6 to 2.9.13 in /app

    Bump vite from 2.9.6 to 2.9.13 in /app

    Bumps vite from 2.9.6 to 2.9.13.

    Changelog

    Sourced from vite's changelog.

    2.9.13 (2022-06-27)

    2.9.12 (2022-06-10)

    • fix: outdated optimized dep removed from module graph (#8534) (c0d6c60), closes #8534

    2.9.11 (2022-06-10)

    2.9.10 (2022-06-06)

    2.9.9 (2022-05-11)

    2.9.8 (2022-05-04)

    ... (truncated)

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependency 
    opened by dependabot[bot] 1
Releases(v7.37.0-next.0)
  • v7.37.0-next.0(Sep 29, 2022)

    ๐Ÿจ feature: include defaultValues inside formState (#8966)

    const { formState, watch } = useForm({
      defaultValues: { name: 'test' }
    })
    const { defaultValues } = useFormState()
    
    const name = watch('name')
    
    return (
      <div>
        <p>Your name was {defaultValues.name}</p>
        <p>Updated name is {name}</p>
      </div>
    )
    

    ๐Ÿ˜ตโ€๐Ÿ’ซ close #9105 improve input focus method check (#9109) ๐Ÿ–จ close #9058 avoid clone object when contains prototype methods

    class DataModel {
      constructor() {
        this.firstName = null
      }
    }
    const formData = new DataModel({ firstName: "Bob" })
    
    useForm({
      defaultValues: formData // no longer get clone internally
    })
    

    ๐Ÿ“– fix UseFieldArrayAppend types example (#9093)

    thanks to @arieloO

    Source code(tar.gz)
    Source code(zip)
  • v7.36.1(Sep 23, 2022)

    ๐Ÿชฒ fix #9082 inconsistency between single/group of checkboxes disabled check state (#9083) ๐ŸŒก๏ธ improve setFocus to prevent throw error (#9081)

    Source code(tar.gz)
    Source code(zip)
  • v7.36.0(Sep 20, 2022)

    ๐Ÿš‚ feature: reset to support callback syntax (#9051)

    reset with partial form values will require invoking getValues at the same time, here is an improvement ๐Ÿ‘‡

    Convert your code from:

    reset({
      ...getValues(),
      partialData: 'onlyChangeThis'
    })
    

    to:

    reset((formValues) => {
      return {
        ...formValues,
        partialData: 'onlyChangeThis'
      }
    })
    
    Source code(tar.gz)
    Source code(zip)
  • v7.35.0(Sep 9, 2022)

    ๐ŸŽ‰ feature: new type FieldPathByValue field path by value generic implementation

    function CustomFormComponent<
      TFieldValues extends FieldValues,
      Path extends FieldPathByValue<TFieldValues, Date>
    >({ control, name }: { control: Control<FieldValues>; name: Path }) {
      const { field } = useController({
        control,
        name,
      });
    }
    
    function App() {
      const { control } = useForm<{
        foo: Date;
        baz: string;
      }>();
    
      return (
        <form>
          <CustomFormComponent control={control} name="foo" /> {/* no error */}
          <CustomFormComponent control={control} name="baz" /> {/*  throw an error since baz is string */}
        </form>
      );
    }
    

    ๐Ÿ›ต close #8969 improve type for useFieldArray rules validate prop #8974

    image

    ๐Ÿ›— upgrade to TS 4.8.0 and Jest 29 #8620 ๐Ÿž fix #8970 register field array cause render issue #8972 ๐Ÿž fix: typings for useWatch() with no arguments #8923 ๐Ÿž fix #8919 make useController fieldState properties enumerable

    const { fieldState } = useController({ name: 'test' })
    const copy = {...fieldState} โœ…
    

    ๐Ÿ‘ถ๐Ÿป close #8909 form context children prop type (https://github.com/react-hook-form/react-hook-form/pull/8910)

    <FormProvider {...methods}>
      <div /> // โœ…
      <div /> // โœ…
    </FormProvider>
    

    ๐ŸŒ allow field errors to escape type check when provided with any type ๐Ÿ” github workflows security hardening #8965 ๐Ÿ’š ci: stop csb ci from publishing a comment on PR (https://github.com/react-hook-form/react-hook-form/pull/8977)

    thanks to @Moshyfawn, @sashashura, @carvalheiro, @chetvishal and @MicaelRodrigues

    Source code(tar.gz)
    Source code(zip)
  • v7.35.0-next.0(Aug 25, 2022)

    ๐ŸŽ‰ feature: new type FieldPathByValue field path by value generic implementation

    function SomeCustomFormComponent<
      TFieldValues extends FieldValues,
      Path extends FieldPathByValue<TFieldValues, Date>
    >({ control, name }: { control: Control<FieldValues>; name: Path }) {
      const { field } = useController({
        control,
        name,
      });
      return null;
    }
    
    function ExampleOfUsage() {
      const { control } = useForm<{
        foo: Date;
        baz: string;
      }>();
    
      return (
        <div>
          <SomeCustomFormComponent control={control} name="foo" />{" "}
          {/* throw no error */}
          <SomeCustomFormComponent control={control} name="baz" />{" "}
          {/*  throw an error since baz is string */}
        </div>
      );
    }
    

    ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8919 make useController fieldState properties enumerable

    const { fieldState } = useController({ name: 'test' })
    const copy = {...fieldState} โœ…
    

    ๐Ÿ‘ถ๐Ÿป close https://github.com/react-hook-form/react-hook-form/issues/8909 form context children prop type (https://github.com/react-hook-form/react-hook-form/pull/8910)

    <FormProvider {...methods}>
      <div /> // โœ…
      <div /> // โœ…
    </FormProvider>
    

    ๐ŸŒ allow field errors to escape type check when provided with any type

    thanks to @carvalheiro, @chetvishal and @MicaelRodrigues

    Source code(tar.gz)
    Source code(zip)
  • v7.34.2(Aug 15, 2022)

  • v7.34.1(Aug 12, 2022)

    ๐Ÿž fix(path): keys of Date | FileList | File shouldn't be add to the PathImpl https://github.com/react-hook-form/react-hook-form/pull/8804 ๐Ÿž fix Date, FileList, File and Blob FieldErrors mapping #8772 ๐ŸšŒ update isSubmitting state after valid form #8829

    function App() {
      const { formState: { isSubmitting }, register } = useForm()
    
      console.log(isSubmitting) // isSubmitting will remain false if form is invalid during submission
    
      return <form onSubmit={handleSubmit(async () => await sleep(1000))}>
        <input {...register('test', { required: true })} />
      </form>
    }
    

    ๐Ÿงƒ upgrade to cypress 10 #8769 ๐Ÿ“– fix nested fields example #8840 ๐Ÿ“– add nested form example #8703 ๐Ÿ“– improve doc of single watch #8773 ๐Ÿ“– fixing typo (Contruรญdo to Construรญdo) on pt-BR translation #8762

    thanks to @HarmonyEarth, @yleflour, @glekner, @vemoo, @ronny1020 and @joaoeffting

    Source code(tar.gz)
    Source code(zip)
  • v7.34.0(Jul 28, 2022)

    ๐ŸŽ‰ feature request: #6879 useFieldArray support rules props (#8102)

    useFieldArray({
      name: 'test',
      rules: {
        required: true,
        minLength: 2,
        maxLength: 10,
        validate: (fieldArrayValues) => {
          if (fieldArrayValues[2].title === 'test') {
            return 'validate Error'
          }
        }
      }
    })
    
    errors?.test?.root?.message // access root level errors
    

    Note: Related context and poll for error message naming: https://github.com/react-hook-form/react-hook-form/discussions/8625

    ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8584: handle nullable nested properties (https://github.com/react-hook-form/react-hook-form/pull/8699) ๐Ÿ†Ž close https://github.com/react-hook-form/react-hook-form/issues/8689 fix type inconsistency with control (https://github.com/react-hook-form/react-hook-form/pull/8691) ๐Ÿž fix native form reset isn't executed if first fieldReference isn't a HTMLElement (https://github.com/react-hook-form/react-hook-form/pull/8678) ๐Ÿž fix useFieldArray action type incorrectness (https://github.com/react-hook-form/react-hook-form/pull/8660) ๐Ÿš” close https://github.com/react-hook-form/react-hook-form/issues/8653 when useFormContext provide no generic for type check (https://github.com/react-hook-form/react-hook-form/pull/8654) ๐Ÿ›ฐ useFormContext include type tests (https://github.com/react-hook-form/react-hook-form/pull/8656) ๐Ÿคฃ fix typo in useForm.ts (https://github.com/react-hook-form/react-hook-form/pull/8645) ๐Ÿ“š README Helper / Sponsor Generation Script / Workflow (https://github.com/react-hook-form/react-hook-form/pull/8676)

    thanks to @@ANTARES-KOR @zandowc @@alexviar @ElectronicsArchiver and @kyoto7250

    Source code(tar.gz)
    Source code(zip)
  • v7.34.0-next.0(Jul 10, 2022)

    ๐ŸŽช feature request: #6879 useFieldArray support rules props (#8102)

    useFieldArray({
      name: 'test',
      rules: {
        required: true,
        minLength: 2,
        maxLength: 10,
        validate: (fieldArrayValues) => {
          if (fieldArrayValues[2].title === 'test') {
            return 'validate Error'
          }
        }
      }
    })
    
    errors?.test?.root?.message // access root level errors
    

    Note: Related context and poll for error message naming: https://github.com/react-hook-form/react-hook-form/discussions/8625

    Source code(tar.gz)
    Source code(zip)
  • v7.33.1(Jul 1, 2022)

    ๐Ÿ fix https://github.com/react-hook-form/react-hook-form/issues/8584: field errors type with optional fields (https://github.com/react-hook-form/react-hook-form/pull/8591) ๐Ÿงณ close https://github.com/react-hook-form/react-hook-form/issues/8600 update code example for NestedValue input ๐Ÿ–ผ Integrate jest-preview into react-hook-form (https://github.com/react-hook-form/react-hook-form/pull/8577) ๐Ÿค“ improve the readability of Merge type (https://github.com/react-hook-form/react-hook-form/pull/8570) ๐Ÿš test: migration from ts-jest to @swc/jest (https://github.com/react-hook-form/react-hook-form/pull/8572) ๐Ÿน refactor: use const instead of props (https://github.com/react-hook-form/react-hook-form/pull/8571) ๐Ÿ” feat: Add ability to search test file on watch mode (https://github.com/react-hook-form/react-hook-form/pull/8573) ๐Ÿง˜๐Ÿป ensure the field is focused when selected (https://github.com/react-hook-form/react-hook-form/pull/8566)

    thanks to @nvh95, @elstgav and @kotarella1110

    Source code(tar.gz)
    Source code(zip)
  • v7.33.0(Jun 24, 2022)

    โš›๏ธ upgrade to react 18 (https://github.com/react-hook-form/react-hook-form/pull/8529) ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8558 missing select function for controlled component (https://github.com/react-hook-form/react-hook-form/pull/8559) ๐Ÿ”ฌ improve nested field errors type (https://github.com/react-hook-form/react-hook-form/pull/8527) ๐Ÿ—‘ UseFormHandleSubmit remove unused generic (https://github.com/react-hook-form/react-hook-form/pull/8526)

    ๐Ÿ‘‹ deprecate on NestedValue and UnpackNestedValue (https://github.com/react-hook-form/react-hook-form/pull/8528)

    type FormValues = {
    -  select: NestedValue<{
    -    nested: string
    -  }>
    +  select: {
    +    nested: string
    +  }
    }
    
    errors.select.message โœ… 
    

    Important (25/06/2022)

    The deprecation with UnpackNestedValue caused a breaking change on the @hookform/resolvers package, please refer to the changelog and upgrade the resolver to the latest.

    ๐Ÿฅผ close https://github.com/react-hook-form/react-hook-form/issues/8564 update changelog for breaking change with resolver ๐Ÿ’ฅ The above type deprecation cause breaking change with @hookform/resolvers needs to be upgraded to version ^2.9.3 above

    Huge thanks go to @felixschorer on type improvement and @romain-trotard for improving tests for react 18

    Source code(tar.gz)
    Source code(zip)
  • v7.32.2(Jun 17, 2022)

    ๐Ÿ‹๐Ÿป improve build dist package size (https://github.com/react-hook-form/react-hook-form/pull/8511) ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8506 delayError not overwrite existing function call (https://github.com/react-hook-form/react-hook-form/pull/8509) ๐Ÿ“– update the use of validadtionSchema in v7 examples (https://github.com/react-hook-form/react-hook-form/pull/8501)

    thanks, @bryantobing12

    Source code(tar.gz)
    Source code(zip)
  • v7.32.1(Jun 14, 2022)

    ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8493 error not trigger with delayError (https://github.com/react-hook-form/react-hook-form/pull/8494) ๐Ÿ” fix null or undefined cases caught by TS ^4.8 (https://github.com/react-hook-form/react-hook-form/pull/8487) ๐Ÿฅธ funnel along with appropriate constraints for (upcoming) TypeScript 4.8 (https://github.com/react-hook-form/react-hook-form/pull/8484)

    thanks to @DanielRosenwasser

    Source code(tar.gz)
    Source code(zip)
  • v7.32.0(Jun 10, 2022)

    ๐ŸŽ  feat: make UseFormRegisterReturn generic over TFieldName (https://github.com/react-hook-form/react-hook-form/pull/8414) ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8459 regression issue with draft state object (https://github.com/react-hook-form/react-hook-form/pull/8463) ๐Ÿงพ fix: doc watch() with callback example must deconstruct the returned type (https://github.com/react-hook-form/react-hook-form/pull/8451) ๐Ÿค fix: compare html elements against correct global (https://github.com/react-hook-form/react-hook-form/pull/8355) ๐Ÿž flush errors state update when user switch input with delayError (#8429)

    thanks to @omjadas @Pika-Pool and @zenoamaro

    Source code(tar.gz)
    Source code(zip)
  • v7.31.3(May 27, 2022)

    ๐Ÿง‘โ€๐Ÿ’ป Support TypeScript 4.7+ ESM (https://github.com/react-hook-form/react-hook-form/pull/8390) ๐Ÿงพ Fix typo (https://github.com/react-hook-form/react-hook-form/pull/8389) โ„น๏ธ fix export types order ๐Ÿช upgrade to TS 4.7 (https://github.com/react-hook-form/react-hook-form/pull/8402) ๐Ÿ•ธ close https://github.com/react-hook-form/react-hook-form/issues/8404 use isWeb instead of globalThis (https://github.com/react-hook-form/react-hook-form/pull/8406) ๐Ÿฅฌ save cloneObject bytes (https://github.com/react-hook-form/react-hook-form/pull/8407)

    thanks to @davbrito, @rossng, @hwanyoungChoi and @Moshyfawn

    Source code(tar.gz)
    Source code(zip)
  • v7.31.2(May 20, 2022)

    ๐Ÿž fix(reset): set isSubmitted to formState value if keepIsSubmitted is true (https://github.com/react-hook-form/react-hook-form/pull/8368)

    thanks to @blabute

    Source code(tar.gz)
    Source code(zip)
  • v7.31.1(May 10, 2022)

    ๐ŸŽญ close #7472 include a proxy check with field state to improve useController perf (#8334) ๐Ÿž fix #8339 Revert "๐Ÿ—‘ remove the reference for blob and file list (https://github.com/react-hook-form/react-hook-form/pull/8305)" ๐Ÿšฎ remove dead code (#8337)

    thanks to @NMinhNguyen

    Source code(tar.gz)
    Source code(zip)
  • v7.31.0(May 10, 2022)

    ๐Ÿš€ reset optional prop: keepDirtyValues (https://github.com/react-hook-form/react-hook-form/pull/8237)

    reset(
      {
        firstName: "bill", // if firstName is dirty then the value will be retained
        lastName: "luo"
      },
      { keepDirtyValues: true } // keep any changed field
    );
    

    ๐Ÿ‘ฉโ€๐Ÿ”ง close https://github.com/react-hook-form/react-hook-form/issues/8324 auto-correct field array errors on user action (https://github.com/react-hook-form/react-hook-form/pull/8325)

    const { append } = useFieldArray()
    
    append({ data: '' }) // will auto correct existing field array errors if any
    

    ๐Ÿž fix: clone objects which have functions (https://github.com/react-hook-form/react-hook-form/pull/8301) ๐Ÿ“– fix name of a new option in 6.12.0 change-log notes (https://github.com/react-hook-form/react-hook-form/pull/8335)

    thanks to @Moshyfawn @airman5573 @TkDodo and @MasterOdin

    Source code(tar.gz)
    Source code(zip)
  • v7.30.0(Apr 17, 2022)

    Notes

    ๐Ÿฃ determine checkbox group by defaultValues set as array value (https://github.com/react-hook-form/react-hook-form/pull/7938)

    useForm({
      defaultValues: {
        checkboxes: [], // register checkbox will be determine as array of checkboxes
      },
    });
    register('checkboxes'); // will return array as value
    

    ๐Ÿงช improve test cases with checkbox default value as array (https://github.com/react-hook-form/react-hook-form/pull/7501) ๐Ÿ“• add fieldState invalid depreciation note (https://github.com/react-hook-form/react-hook-form/pull/8202) โ›‘ improve getNodeParentName missing case(s) (https://github.com/react-hook-form/react-hook-form/pull/8181) ๐Ÿ”จ support field array parents with numbers in name (https://github.com/react-hook-form/react-hook-form/pull/8167) ๐Ÿ’‰ improve lib tests cases (https://github.com/react-hook-form/react-hook-form/pull/8155)

    Contributors

    Thanks to contributors below โค๏ธ

    • @spacenate
    • @tedliang
    • @Moshyfawn
    • @jgullstr
    • @romain-trotard
    Source code(tar.gz)
    Source code(zip)
  • v7.29.0(Mar 30, 2022)

    โค๏ธ update react 18 peer dep ๐Ÿ“ฆ es2017 to es2018 (https://github.com/react-hook-form/react-hook-form/pull/8066) Reduce 1% of package weight ๐Ÿƒ avoid runtime error with compact (https://github.com/react-hook-form/react-hook-form/pull/8094) ๐Ÿ‘‹ goodbye omit (https://github.com/react-hook-form/react-hook-form/pull/8079) ๐Ÿž close https://github.com/react-hook-form/react-hook-form/issues/8071 issue on shouldUnreigster mutate defaultValues (https://github.com/react-hook-form/react-hook-form/pull/8078) โญ๏ธ close https://github.com/react-hook-form/react-hook-form/issues/8076 isMount flag issue with useEffect running twice with react 18 (https://github.com/react-hook-form/react-hook-form/pull/8077) ๐ŸŽง close https://github.com/react-hook-form/react-hook-form/issues/8071 clean up at useForm useEffect (https://github.com/react-hook-form/react-hook-form/pull/8073)

    Source code(tar.gz)
    Source code(zip)
  • v7.28.1(Mar 20, 2022)

    ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8050 disabled attribute ignored with register checkbox (https://github.com/react-hook-form/react-hook-form/pull/8053) ๐Ÿ“ฆ update package.json to set sideEffect false (https://github.com/react-hook-form/react-hook-form/pull/8041) ๐Ÿ†™ TS 4.6.0 (https://github.com/react-hook-form/react-hook-form/pull/7623) ๐Ÿ“– fix replace API TSDoc for fieldArray

    thanks to @alexogar and @Moshyfawn

    Source code(tar.gz)
    Source code(zip)
  • v7.28.0(Mar 13, 2022)

    ๐Ÿฌ enable deps with string syntax (https://github.com/react-hook-form/react-hook-form/pull/7901)

    register('test', { deps: 'theOtherInput' })
    register('test', { deps: ['theOtherInput', 'others'] })
    

    ๐Ÿงท fix field array update to avoid external mutation ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/7960 issue on unset deeply nested array field (https://github.com/react-hook-form/react-hook-form/pull/7961) ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/7958 issue with checkbox plus portal (https://github.com/react-hook-form/react-hook-form/pull/7959) ๐Ÿ“ฆ unpack blob data type (https://github.com/react-hook-form/react-hook-form/pull/7937)

    thanks to @DASPRiD and @Moshyfawn

    Source code(tar.gz)
    Source code(zip)
  • v7.28.0-next.0(Feb 26, 2022)

    ๐Ÿฌ enable deps with string syntax (https://github.com/react-hook-form/react-hook-form/pull/7901)

    register('test', { deps: 'theOtherInput' })
    

    ๐Ÿงท fix field array update to avoid external mutation

    Source code(tar.gz)
    Source code(zip)
  • v7.27.1(Feb 19, 2022)

    ๐Ÿ› fix https://github.com/react-hook-form/react-hook-form/issues/7853 (useFieldArray): pass context type down to Control (https://github.com/react-hook-form/react-hook-form/pull/7856) ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/7849 issue with unset on multiple dimension array (https://github.com/react-hook-form/react-hook-form/pull/7859)

    thanks to @Moshyfawn

    Source code(tar.gz)
    Source code(zip)
  • v7.27.0(Feb 11, 2022)

    โœจ https://github.com/react-hook-form/react-hook-form/issues/7138 feature: allow selecting input's content on focus (https://github.com/react-hook-form/react-hook-form/pull/7781)

    setFocus('fieldName', { shouldSelect: true })
    

    https://user-images.githubusercontent.com/10513364/153570934-ca29337f-d7ce-4744-b282-6939c2e17b48.mp4

    โŒจ๏ธ fix https://github.com/react-hook-form/react-hook-form/issues/7772 type issue by using UnpackNestedValue on FieldArray methods (https://github.com/react-hook-form/react-hook-form/pull/7773)

    thanks to @Moshyfawn and @hpersson

    Source code(tar.gz)
    Source code(zip)
  • v7.26.1(Feb 7, 2022)

    ๐Ÿž close https://github.com/react-hook-form/react-hook-form/issues/7758 useController should subscribe to exact field name (https://github.com/react-hook-form/react-hook-form/pull/7759)

    thanks to @Moshyfawn

    Source code(tar.gz)
    Source code(zip)
  • v7.26.0(Feb 4, 2022)

    ๐Ÿ“š TSDoc

    https://user-images.githubusercontent.com/10513364/152477495-7df7269c-18c2-4420-85e7-956c7c35ca42.mp4

    ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/7741 is validating reset when async validations are still running (https://github.com/react-hook-form/react-hook-form/pull/7747) โ›‘ close https://github.com/react-hook-form/react-hook-form/issues/7717 shallow clone errors object in handleSubmit (https://github.com/react-hook-form/react-hook-form/pull/7718) ๐Ÿฆ close https://github.com/react-hook-form/react-hook-form/issues/7703 don't expose internal state in handleSubmit (https://github.com/react-hook-form/react-hook-form/pull/7704) ๐Ÿ‹๏ธ save bytes on parseFloat (https://github.com/react-hook-form/react-hook-form/pull/7697)

    thanks to @Moshyfawn and @tiii

    Source code(tar.gz)
    Source code(zip)
  • v7.25.3(Jan 29, 2022)

  • v7.25.2(Jan 28, 2022)

  • v7.25.1(Jan 25, 2022)

    ๐Ÿž fix #7662 issue with reset file input (#7656) ๐Ÿš— improve perf with get proxy formState (#7655) ๐Ÿ‹๏ธ remove redundant check (#7651) ๐Ÿž fix #7648 Unable to setFocus to Controller after reset (#7649) ๐Ÿž fix: getFieldState - error might be undefined (#7636) โ›‘ improve useFieldArray code consistency (#7628)

    thanks to @Moshyfawn and @michalbundyra

    Source code(tar.gz)
    Source code(zip)
Owner
React Hook Form
๐Ÿ“‹ React hooks for form validation without the hassle
React Hook Form
๐Ÿ‘ฉโ€๐Ÿณ A React Hooks utility library containing popular customized hooks

React Recipes A React Hooks utility library containing popular customized hooks What's your favorite dish? npm i react-recipes --save yarn add react-r

Craig Walker 905 Sep 19, 2022
๐Ÿน A lot of nice hooks to make react hooks easier to use ( useState callback / life cycle / instance variable)

?? Nice Hooks ไธญๆ–‡็‰ˆ A lot of nice hooks to make react hooks easier to use. If you find this project is useful to you, please give me a star. Installatio

Daniel.xiao 45 May 5, 2022
๐Ÿ”ฅ A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development ๐Ÿ”ฅ

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development ?? Live playground here ?? ???? English

Antonio Rรน 6k Sep 22, 2022
Learn the more advanced React hooks and different patterns to enable great developer APIs for custom hooks

?? Advanced React Hooks ?? EpicReact.Dev Learn the more advanced React hooks and different patterns to enable great developer APIs for custom hooks. W

Josรฉ Gonรงalves 4 Mar 15, 2022
Use-supabase-hooks contains react hooks for common supabase functions, with type safety!

Use-supabase-hooks contains react hooks for common supabase functions, with type safety!

Anurag 14 Sep 30, 2022
ReactJs Custom hooks, component lifecycle - Indispensable hooks

ReactJs Custom hooks, component lifecycle - Indispensable hooks

Alan Buscaglia 54 Sep 23, 2022
useFormless allow you to control forms in React using react-hook approach

useFormless react-useformless is a simple library that allows you to control forms with react-hooks approach Why useFormless? Works with nested forms

Gibran LM 49 Jul 10, 2022
React validatable form hook that is used to create dynamic client side validations on react forms

React Validatable Form React validatable form hook that is used to create dynamic client side validations on React forms. Table of Contents Install Ge

Open Business Software Solutions 19 Aug 25, 2022
๐Ÿ“„ React hook for managing forms and inputs state

react-use-form-state ?? Table of Contents Motivation Getting Started Examples Basic Usage Initial State Global Handlers Advanced Input Options Custom

Waseem Dahman 941 Sep 27, 2022
React custom hooks for web workers

react-hooks-worker React custom hooks for web workers. Introduction Web Workers are another thread from the main thread in browsers. We can run heavy

Daishi Kato 610 Sep 21, 2022
React hooks web application built as presentation tool for my tech talk, sponsored by SingleSprout.

React Hooks Presentation This react application was built to educate on the basics of React Hooks, and to demonstrate the functionality of 3 primary R

Roland Wynter 5 Jun 28, 2021
A simple Hooks wrapper over Motion One, An animation library, built on the Web Animations API for the smallest filesize and the fastest performance.

A simple Hooks wrapper over Motion One, An animation library, built on the Web Animations API for the smallest filesize and the fastest performance.

Tanvesh Sarve 88 Sep 26, 2022
React Native APIs turned into React Hooks for use in functional React components

React Native Hooks React Native APIs turned into React Hooks allowing you to access asynchronous APIs directly in your functional components. Note: Yo

React Native Community 2.9k Sep 22, 2022
Travel Website is a React application that uses React Hooks and React Router for this beginner React JS Project

Travel Website is a React application that uses React Hooks and React Router for this beginner React JS Project. The website is fully responsive as well.

Leticia Lumi Nagao 3 Aug 28, 2022
React-cache-api - React Cache API is a React Hooks library for data fetching

React Cache API React Cache API is a React Hooks library for data fetching. It w

awmaker 12 Aug 31, 2022
:tada: React Universal Hooks : just use****** everywhere (Functional or Class Component). Support React DevTools!

react-universal-hooks React Universal Hooks : just use****** everywhere. Support React >= 16.8.0 Installation Using npm: $ npm install --save react-un

Salvatore Ravidร  175 Aug 1, 2022
Lightweight React bindings for MobX based on React 16.8 and Hooks

mobx-react-lite ?? ?? ?? This repo has been moved to mobx This is a lighter version of mobx-react which supports React functional components only and

MobX 2.1k Sep 15, 2022
A delightful modal dialog component for React, built from the ground up to support React Hooks.

?? modali A delightful modal dialog library for React, built from the ground up to support React Hooks. Modali provides a simple interface to build be

Upmostly 204 Sep 23, 2022