Git Product home page Git Product logo

react-hook-form's Introduction

npm downloads npm npm Discord

Get started | API | Form Builder | FAQs | Examples

Features

Install

npm install react-hook-form

Quickstart

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

function App() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <input {...register('firstName')} />
      <input {...register('lastName', { required: true })} />
      {errors.lastName && <p>Last name is required.</p>}
      <input {...register('age', { pattern: /\d+/ })} />
      {errors.age && <p>Please enter number for age.</p>}
      <input type="submit" />
    </form>
  );
}

Sponsors

Thanks go to these kind and lovely sponsors!

Past sponsors

Backers

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

Contributors

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

react-hook-form's People

Contributors

ayumikai avatar barrymay avatar bluebill1049 avatar daisuke85a avatar dandv avatar felixschorer avatar jantimon avatar jeromedeleon avatar jgullstr avatar jorisre avatar kabriel avatar keiya01 avatar kotarella1110 avatar ldanet avatar leapful avatar lincerossa avatar michalbundyra avatar michaltarasiuk avatar moshyfawn avatar neighborhood999 avatar nickman87 avatar nvh95 avatar petercpwong avatar pmaier983 avatar simplycomplexable avatar ssi02014 avatar stramel avatar tanmen avatar tiii avatar yi-tuan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-hook-form's Issues

fieldarray

hello
there are plans to add field array like reduxform? or simply with this lib, it's needed another techniques ?

Issue with async submit

Describe the bug
if you provide an async submit handler, the isSubmitting will not be updated correctly

To Reproduce
Steps to reproduce the behavior:

  1. add async submit handler that takes 2sec to finish
  2. notice the form state will not show isSubmitting for those 2 seconds

Expected behavior
isSubmitting should be true while submit handler is pending

Additional context
To work around this issue (not claiming this is a fix because i do not know the code well) I patched my version with the following:

https://github.com/bluebill1049/react-hook-form/blob/2bf73dddbb043963e4f61b799b7b1f884b6acad7/src/index.ts#L344

before:

    if (isEmptyObject(fieldErrors)) {
      callback(combineFieldValues(fieldValues), e);
    } else {
      errorsRef.current = fieldErrors;
      reRenderForm({});
    }

after:

    if (isEmptyObject(fieldErrors)) {
      await callback(combineFieldValues(fieldValues), e);
      reRenderForm({});
    } else {
      errorsRef.current = fieldErrors;
      reRenderForm({});
    }

this awaits on the promise returned by the onSubmit handler (seems this is required if you intend to support async submit handlers as the docs claim) and then re-renders the form so all form state can update

Using yup with onChange or onBlur mode

Describe the bug
onChange and onBlur mode doesn't work with yup validation schema or I miss something :)

To Reproduce
Steps to reproduce the behavior:

  1. Open ValidationSchema example: https://codesandbox.io/s/928po918qr
  2. Set mode: 'onBlur:
const { register, handleSubmit, errors } = useForm({
    mode: 'onBlur',
    validationSchema: SignupSchema
  });
  1. Change the firstName and/or age fields and watch stringified errors object.

It looks like that clearing error works OK, but setting error does not.

Expected behavior
Expected error message for empty firstName field after leaving field.

Desktop (please complete the following information):

  • OS: macOS 10.14.4
  • Browser chrome, 73.0.3683.103

Array inside form model

Hi, I started using this plugin recently, and it's great. I have forms that their model contains arrays, so I need some sort of looping. I know that you do that, but you save the paths as keys and the form values end up something like this:
{ "title": "my form", "people[0].name": "peter", "people[1].name": "john" }

whereas the model is like below
{ "title": "my form", "people": [ { "name": "peter"}, { "name": "john" } ] }

In my case I am using the set function from lodash to map the form object inside onSubmit to my business model.

Something like set(newModel, 'people[0].name', 'peter') works fine.

So, I was wondering if you could use in your api a function like "set" so you can assign complex paths a value, and then also gain the benefits of TS for the "errors" object, where you can access to errors.people[0].name. I think that as a result, your form data will reflect the business model which can be beneficial.

🏎 Performance of ref API

Hi, I am opening a regular issue as I was not sure what to open, feel free to close if inappropriate.

You chose a different API than other library authors on how to register input elements in the form state. Most other libs use some kind of helper like <input {...registerField({ name: 'abc', ...)} />.

I tend to prefer yours because it looks cleaner in the code. Do you see any downsides? Is there a performance tradeoff that you know of? What happens under the hood? Are you bailing out of standard react APIs? Do you have to use DOM elements directly, or use DOM event binders? (which other may not have to, as they use standard props / event binders)

Any insight appreciated, on performance or otherwise.

Thanks for the library 👍

[Question] `errors` type completion doesn't work well.

Hi, thanks for the great form library.
I'm trying version 3.8.6 with typescript, but errors type completion doesn't work well.

Demo

type FormData = {
  name: string;
};

const App: React.FC<SomeProps> = props => {
  const defaultValues: FormData = {
    name: props.name
  };
  const { register, handleSubmit, errors } = useForm<FormData>({
    mode: "onSubmit",
    defaultValues,
  });

  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <input
        name="name"
        ref={register({ required: "name is required." })}
      />
      {errors.name && errors.name.message}
      // Property 'name' does not exist on type 'typeof' ErrorMessages<FormData>

      <input type="submit" />
    </form>
  );
};

I read the source code and think this line is the cause.
https://github.com/bluebill1049/react-hook-form/blob/97952827cb90e145622e9f3c28087e91c3ff9f95/src/types.ts#L61

Do you think | {} is needed? Or, I'm glad you tell me the workaround.

After first submit with error values, the form can't be submitted again

Describe the bug
I am using react-hook-form with nextjs. After I submit my form for the first time (with intended errors) it works fine. But when I remove the errors (edit the values of inputs) I can't submit the form again hence the errors don't disappear and the whole form doesn't react to submitting.
I have to refresh the page.

Expected behavior
Expected behavior would be that the errors disappear and the form gets submitted again.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: Chrome
  • Version: 75.0.3770.80

Additional context
Add any other context about the problem here.

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

Small `register` API suggestion

Minor suggestion but it looks like if you used a closure then the register API could perhaps be simpler?

function register(data = {}) {
  return (ref) => {
    // etc.
  }
}
<input type="text" name="firstname" ref={register({ required: true })} />
<input type="text" name="lastname" ref={register()} />

removeEventListener Problem

useEffect cleanup function
Sorry about my bad english. I wanted to use your library with GRAPHQL. There are two forms in my project,one was made with FORMIK and the other with REACTHOOKFORM.
Listeners get alert for clearance.

warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

You can get the project out of here.
https://github.com/FatihErtugral/NodeJsExercise

import React from 'react';
import { Mutation, ApolloConsumer } from 'react-apollo';
import gql from 'graphql-tag';

import { LoginForm } from './LoginForm';

const LOGIN_USER = gql`
  mutation Login($Email:String!, $Password:String!){
    Login(input:{
      Password:$Password,
      Email:$Email
    }){
      token
    }
  }
`;
export const Login = ()=>{
  return (
    <ApolloConsumer>
      {client => (
        <Mutation
          mutation={LOGIN_USER}
          onCompleted={({ Login }) => {
            Login.token && localStorage.setItem('token', Login.token );
            client.writeData({ data: { isLoggedIn: true } });
          }}
        >
          {(login, { loading, error }) => {
            if (loading) return <p>loading...</p>;
            if (error) return <p>{error.message}</p>;

            return (<LoginForm login={login} />);
          }}
        </Mutation>
      )}
    </ApolloConsumer>
  );
}
import React from "react";
import { TextField, Button, Paper } from '@material-ui/core';
import useForm from 'react-hook-form'
import {Link} from 'react-router-dom';

export const LoginForm = ({login}) => {

  const { register, handleSubmit, errors } = useForm({ mode: "onSubmit" });
  const onSubmit = (data, e) => {
    e.preventDefault();
    return login({ variables: { Email: data.Email,Password:data.Password } });
  };

  return (
    <div className="outer">
      <div className="middle">
        <div className="inner">
          <div className="container">
            <div className="row justify-content-center">
              <Paper id='paper' className='col-xl-4 col-lg-4 col-md-12 col-sm-12 col-12'>
                <h2 id='loginHeader' className='formItem'>Giriş Yap</h2>
                <form id="fatih" method='POST' onSubmit={handleSubmit(onSubmit)}>

                  <div className="formItem">
                    <TextField
                      inputRef={register({
                        maxLength: { value: 20, message: 'Maximum 20 karakter olabilir.' },
                        minLength: { value: 3, message: 'Minimum 3 karakter olabilir.' },
                        required: 'Bu alan zorunludur'
                      })}
                      name="Email"
                      type="text"
                      label="Kullanıcı Adı"
                      error={!!errors.Email}
                      helperText={errors.Email && errors.Email.message}
                      fullWidth
                    />
                  </div>

                  <div className="formItem">
                    <TextField
                      inputRef={register({
                        maxLength: { value: 20, message: 'Maximum 20 karakter olabilir.' },
                        minLength: { value: 3, message: 'Minimum 3 karakter olabilir.' },
                        pattern: {
                          value: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
                          message: 'En az sekiz karakter, en az bir harf, bir sayı ve bir özel karakter'
                        },
                        required: 'Bu alan zorunludur'
                      })}
                      name="Password"
                      id="Password"
                      type="Password"
                      label="Parola"
                      error={!!errors.Password}
                      helperText={errors.Password && errors.Password.message}
                      fullWidth
                    />

                  </div>

                  <div className="formItem ">
                    <Button

                      type="submit"
                      fullWidth
                      variant="contained"
                      color="primary"
                    >GİRİŞ YAP
                     </Button>
                  </div>

                  <div className="formItem ">
                    <Link to='/register'>Üyeliğiniz yokmu kayıt olun</Link>
                  </div>
                </form>
              </Paper>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Despite setting to 'onSubmit', Input validation occurs on blur

I have set validation mode to onSubmit (It is default value). But, validation occurs on input blur.
This is how I register my input:

 <input
        ref={register({ required: true })}
        name="password"
        type= "password"
      />

When leaving the input, required error appears on page.
I use V 3.8.9

Debounce async validation function calls when mode is `onChange`

Hi guys — First of all, thumbs up for this super cool library 👍

I recently noticed that when the validation mode in onChange and I have a field which performs async validation, the function is called every time the field changes, which is kind of wasteful. It would be nice to have a debounce functionality so the async function isn't called every time.
The usual scenario si when a user is typing on a field and I only want to validate when the typing is done, I don't care about validating on each keystroke.
This behavior is slightly better IMHO than the onBlur alternative, because the user could get a feedback when the focus is still on the field that is being filled in. And the feedback shouldn't "harass" the user.

Please see this example for reference (open the dev console and type in the Username field).
https://codesandbox.io/s/react-hook-form-async-field-validation-50cyw

Is there a way I can achieve debouncing already? Am I missing something?
Thanks for your attention.

[Feature Request] Trigger validation programatically

Is your feature request related to a problem? Please describe.

If a user doesn't enter a value, the validation doesn't happen until submission. However, if I am in a wizard (a single form has multiple steps), I want to prevent someone from continuing to the next step. If someone clicks the next button, the fields are not checked so the user cannot be prevented.

Describe the solution you'd like

I'd like a function returned by useForm to trigger a validation of the fields. Bonus points to also accept string | string[] fields to only validate given fields.

Describe alternatives you've considered

Currently I have to also use getValues but this doesn't show the error message then:

validate: (): boolean => !errors.title && Boolean(getValues().title),

I'd like to do:

validate: (): boolean => validate('title')

And the errors object then have an error (if the field is invalid) so that my form can show the error also. From what I've seen in the code, the validation is only internal and no way for me to get to it easily and the different modes don't handle if the field was never focused.

[Feature Request] Array fields

I will be working on this array fields very soon.

at the moment the api in my head will be like the below:

[1,2,3].map((i) => <input name={`test[$i]`} key={i} ref={register} />);

Checkbox value

Hi,

I have a form with checkboxes in it with a value attribute set.

               <input
                  name={`device-${num}`}
                  type='checkbox'
                  value={device.id}
                  ref={register}
                />

When I use getValues() - It returns an object with "device-1": true, "device-2": false rather than the device.id value.

Src:
https://github.com/bluebill1049/react-hook-form/blob/master/src/logic/getFieldValue.ts#L12

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

According to the spec - I'd like for the value to be the value set on the input box when it is checked. Something like checked ? value : false

setValue() doesn't dirty the form

Describe the bug
I use setValue to update a field

To Reproduce
Create a form with an input and use a button to update it via setValue or triggerValidation (which calls setValue)

You can see an example here:
https://codesandbox.io/s/react-hook-form-trigger-validation-1dn2h
notice when you press the submit button, the fields update, the form is still not dirty

Expected behavior
I would expect changing a form value via setValue would dirty the form (otherwise we can't update the form from complex ui controls)

I don't have a fix for this yet, it looks more complex than a few lines.

Initialize form values

Hi! Thanks for making this awesome library!
I have a question, how do you initialize form values? Is there such a feature?

Works with PrimeReact's InputText ?

Hi,

First, sorry for my bad english :)

The register method does not work with PrimeReact components.
Do you have any way to use it correctly?
I have tried in many ways that I read in the documentation and on the forums.
Nothing worked :(

Can you help me ?

Thanks

Rafael.

website issues

  1. api not update with watch and validate
  2. overflow x need to be hidden for codes

[Question] Arrayfields data object

Hi, don't know if this is right place for questions, but now I try :)

In my project I have a fields array of products and I want the data to come out something like this:

products: [ 
  {
    name: "iPhone",
    description: "Overpriced hyped smart phone"
  },
  {
    name: "Huawei",
    description: "Chinese spying tool"
  }
]

But from looking at the fieldsArray example can only seem to get:

{
  products.name["iPhone", "Hauwei"]
  products.description["Overpriced hyped smart phone", "Chinese spying tool"]
}

I know, I'm doing something wrong, but is it possible to get what I want, by just writing the input name in a certain manner?

Best regards Nikolas

Changing input clears all errors

Describe the bug
react-hook-form version: 3.8.2

If I create several inputs with simple require: true option then changing one input clears errors for all other inputs.

I believe it was caused by this change in filterUndefinedErrors util: 60f067f#diff-214650c784ae501eee5389467af3c9a8
Since value.isManual is undefined for each value the reduce returns empty object

To Reproduce

  1. Create 2 inputs with ref={register({require:true})}
  2. Submit the form (two errors should be shown for each input)
  3. Change value for one input
  4. All input errors are cleared

Expected behavior
4. The error should be cleared only on the input which validation error was fixed

Run Prettier over Docs?

Thanks for this lib! The patterns look great.

The docs are a bit difficult to read however because the code samples seem to be formatted by hand. Prettier supports Markdown, which would improve readability overall. Also the code samples are a bit small text-size-wise and line-height-wise, requiring a bit of squinting.

Validate component with State.

Describe the bug
If the validated component has the State, then the input is blocked.

// Form
<form onSubmit={handleSubmit(onSubmit)}>
            <div>
              <Input
                name="phone"
                error={errors.phone && errors.phone.message}
                forwardedRef={register({ 
                  validate: (value) => {
                    if (value.length < 4)
                      return CONSTANTS.INPUT_ERROR_PHRASE.EMPTY_FIELD
                    if (value.length >= 4 && value.length < 18)
                      return CONSTANTS.INPUT_ERROR_PHRASE.INVALID_FIELD
                  }}
                )}
              />
            </div>
</form>
// Input
interface IState {
  value: string;
}
export class Input extends Component<InputProps, IState> {
  onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value  = this.setMask(event.target.value);
    this.setState({ value });
    this.props.onChange && this.props.onChange(event);
  }
  render () {
    return (
        <input
          name={name}
          value={this.state.value}
          ref={forwardedRef}
        />
    );
  }
}

I suspect because of the re-render form, the event on onChange is not calls.

  • Browser Chrome, Safari, Edge
    in Firefox not reproduced.

Failed to minify the code from this file

Hi,

Great work doing this, I've been using it for form building in my app. However I'm having one important issue when running npm run build (the app was created with create-react-app). The issue is:

Failed to minify the code from this file:

        ./node_modules/react-hook-form/dist/index.es.js:9:44

I've tried updating react-scripts to v.2.0.0 but the problem remains. Any idea how to solve this?

Register by name breaks validation

Describe the bug
I am trying to connect a SemanticUI controlled component to the hook-form lib.
I am using

  useEffect(() => {
    register({ name: "somename" }, { required: true })
  }, [])

const onChange = (e) => {
    setValue("somename", e.target.value)
  }

to connect it.

However, the validation behaves in a weird way:

  • When trying to fill out the input field in a valid way and submit, it works
  • When trying to first submit a not valid form, fill it out afterwards and submit, it still gives an validation error

To Reproduce
Minimal example:
https://codesandbox.io/s/rough-pine-p8ypz?fontsize=14

2019-06-07 11 53 48

Expected behavior
Validation should work after:

  • submitting an invalid form
  • input valid data
  • submitting again

Desktop (please complete the following information):

  • OS: MacOS
  • Browser Chrome

Ability to transform value

Is there a way to apply value transformations on cnange event?
For example, I'd like to trim() some field values and if it's a credit card field I want to add white spaces after each 4th digit

setValue() doesn't add field to formState.touched

I'm using a date picker and it's not simple <input /> so I manually add a hidden field for it:
<input ref={register} name="date" type="hidden" defaultValue={dateStr} />

And when user change/select a date, I use:
setValue('date', dateStr);

Everything works well, I can see that field's value changed by watch(). But in formState.touched, it doesn't contain date.

Is it a bug or I did something wrong? If it's a bug, is there a way to manually add field(s) to formState.touched?

Failed to minify the code from this file

Copy of issue #50

Hi,

Great work doing this, I've been using it for form building in my app. However I'm having one important issue when running npm run build (the app was created with create-react-app). The issue is:

Failed to minify the code from this file:

    ./node_modules/react-hook-form/dist/index.es.js:9:44

I've tried updating react-scripts to v.2.0.0 but the problem remains. Any idea how to solve this?

Handle custom form components with useImperativeHandle

I have a custom form component with several input and I have forwarded register ref with forwardRef.
I have used useImperativeHandle like this. But it seems that the value is not going to be updated by "value" change. I think there should be a simple support for custom form components; (value is array)

useImperativeHandle(
    ref,
    () => {
      return {
        type: "text",
        name: "name",
        value: value.join("")
      };
    },
    [value]
  );

[Question] Integration with React UI Frameworks

Hi @bluebill1049 , first, congrats for you tool. Its very easy to use and usefull.

Its my first github issue, tell me if I do something wrong.

I try to use react-hook-form with Evergreen UI but doesnt work with a components from this framework.

If i use text input component, the validation doesnt show. But works ok when I change <TextInput /> component for a simple <input /> component.

I created a codesandbox example to see the case better.

Thansk for you time!,
✌️

[Feature request] Clear form

Is your feature request related to a problem? Please describe.

I don't know how to cleanup the form when using this library, because it's uncontrolled.

Describe the solution you'd like

Add a clear function in the hook returned object. Suggested API:

  • clear() clear all fields of that form
  • clear('field1', 'field2')clear only the specified fields
  • TBD how to deal with initial values? should this revert to empty, or initial value? idk (and I do not use initial values so far in my use case)

Describe alternatives you've considered

  • Add a ref myself on every input (which is a bit more complicated because of register function) and then imperatively set their value empty (or initial value) on each of them.
  • Make all input also controlled and use that to clear their value

Or maybe I'm missing something and this feature already exists? :)

Intercepting ref

Is your feature request related to a problem? Please describe.
Let's say for whatever reason, I need to pass my own ref function to an input, we currently don't have a way to do that.
Describe the solution you'd like
<input ref={register({ ref })}>

Custom Input validation

Hello, I can't seem to figure out why the validation doesn't work on custom inputs like Select2.

I have created a fork of your custom input example, which already registers the select input, so I just added the required validation, now I expect that the reactSelect value will be available when the onSubmit function is triggered, but it's missing from data.

Screenshot_2019-05-24_11-55-42

My understanding is that required validation will make sure all inputs values are available when the onSubmit function is triggered. Maybe I am wrong? I also can't seem to make other validation rules work for custom input.

How would you go about solving this? setError maybe?

and Thank you for creating this.

Invariant Violation: Invalid hook call

Describe the bug
I tried to use the library with my React app today, crashes as soon as I use the hook in my code.

Uncaught Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

some relevant package versions from my package.json:

    "react-dom": "^16.8.6",
    "react-hook-form": "^3.9.0",
    "react-redux": "^7.0.3",
    "react-router": "^5.0.1",
    "react-router-dom": "^5.0.1",
    "react-hook-form": "^3.9.0",

Everything is up-to-date at the time of writing this.

To Reproduce
Steps to reproduce the behavior:

  1. Install the currently latest versions of react related libraries
  2. Use useForm() in a functional component.
  3. Observe the exception

Expected behavior
The app should not crash.

Desktop (please complete the following information):

  • OS: Windows
  • Browser Chrome
  • Version 69.0.3497.92

Additional context
might be related to this

ReactStrap Input error

I using input from reactstrap and doesn't work.
in registerIntoFieldsRef just got undefined in elementRef.type and elementRef.value.

import { Input} from 'reactstrap'
<Input type="text" name="catalogName" value={inputChange.catalogName} onChange={handleInputChange} placeholder="Nome" ref={register({ required: true, name: 'catalogName' })} />
Screen Shot 2019-05-29 at 08 51 16

manually register({name: 'fieldname'}) doesn't include init/default value, and causes error when reset form

If I register a field manually like this:
useEffect(() => { register({ name: 'fieldname' }); }, []);
or like this:
<MyCustomInput ref={e => register({ name: 'fieldname' })} />

I found 2 problems:

  1. This field's value is not set (undefined) while other are set (checked by watch()).
  2. When I reset() this form, it throws an error:
    TypeError: Object.values(...)[0].ref.closest is not a function

Screenshot at May 31 16-46-23


Also, about the second approach (ref={e => register(...)}) I followed your example in documentation:
Screenshot at May 31 16-49-38

But I don't understand how it works, the e hasn't been used at all. In React official documentation, it doesn't mention there is an e in ref too. Could you help me to understand this?

Using the react-hook-form in class component

How do i add the hook into a class component? the current examples show only to add it to function component?

Getting this error when I try to add it in a function

Uncaught Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
    at invariant (http://localhost:3000/bundle.js:45863:15)
    at Object.throwInvalidHookError (http://localhost:3000/bundle.js:58675:3)
    at useRef (http://localhost:3000/bundle.js:70887:21)
    at useForm (http://localhost:3000/bundle.js:67453:75)
    at BannerReport.render (http://localhost:3000/bundle.js:82491:85)
    at finishClassComponent (http://localhost:3000/bundle.js:60549:31)
    at updateClassComponent (http://localhost:3000/bundle.js:60504:24)
    at beginWork (http://localhost:3000/bundle.js:61452:16)
    at performUnitOfWork (http://localhost:3000/bundle.js:65120:12)
    at workLoop (http://localhost:3000/bundle.js:65160:24)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.