I've been running into an issue when trying to set a default value for a custom input component. I've experimented with using getValues()
and watch
, but both return an empty value on the first render.
See below to replicate the issue. The custom input field is empty on load, but will populate after entering text in any of the other fields.
https://codesandbox.io/s/react-hook-form-bug-2ltts
Hi @jasondibenedetto ,
Thanks for reporting this issue.
For custom input, you will have to register the defaultValue
manually. Because running the following code
register({ name: 'test' })
doesn't give React Hook Form the context of its ref. Your default value will be injected into the hook but not on the DOM input.
vice versa when you running <input ref={register} />
React Hook Form have access to your input and hence it's working.
so for custom input, you will have to do <input defaultValue={defaulValues.xxx} />
watch
will always return undefined for the initial render, it watches when the input changes.
let me know if this makes sense.
cheers
bill
That all makes sense to me, thank you for the direction @bluebill1049
my pleasure, feel free to ask more questions or raise issues here.
have a nice day :)
Most helpful comment
Hi @jasondibenedetto ,
Thanks for reporting this issue.
For custom input, you will have to register the
defaultValue
manually. Because running the following coderegister({ name: 'test' })
doesn't give React Hook Form the context of its ref. Your default value will be injected into the hook but not on the DOM input.
vice versa when you running
<input ref={register} />
React Hook Form have access to your input and hence it's working.so for custom input, you will have to do
<input defaultValue={defaulValues.xxx} />
watch
will always return undefined for the initial render, it watches when the input changes.let me know if this makes sense.
cheers
bill