Hi,
I noticed an error (see https://codesandbox.io/s/react-hook-form-custom-input-b5lll?fontsize=14). On the Material UI field the first key you type doesn't write, it doesn't work, the input starts filling only after the second keystroke. The bug appears only on registered components.
Thank you for you help and again for the lib,
Cheers
hey @Romcol ,
react hook form leverages uncontrolled input, so you just need to change the value
into defaultValue
:)
cheers
Hi,
Thank you for the quick answer. Most of my inputs are controlled inputs... What if I want to perform edits on those fields? (Such as https://codesandbox.io/s/react-hook-form-custom-input-x0zgw) It's too bad because apart from this problem, everything seems to work...
Thanks!
you can still use controlled input, but use defaultValue
instead of value
:)
<InputField onChange={handleChange} defaultValue='xxx' />
Well, yes but in the example '/' is not replaced by '-' when typing into the field. IMO, the field is not being controlled anymore. Cheers
check the example again, I have updated the code sandbox
https://codesandbox.io/s/react-hook-form-custom-input-7tyw2
also, I have an example for masking
Normalize/Format/Mask Field | https://codesandbox.io/s/387z7njwzp
there are lots of examples you can check out here too :)
https://github.com/bluebill1049/react-hook-form/tree/master/examples
Cool, thanks :) Not sure it covers all use case though. Will look into it later.
no worries, feel free to ask questions here :) we using react hook form at my work in production, it should be fine 👍
hey @Romcol just a quick follow up, how did you go with this issue?
Hi, thanks for following up!
I managed to do pretty much what I wanted switching to uncontrolled fields. I actually thought the lib allowed to register Material UI select textfields with inputRef (because there's no way not to control this component) but I found it impossible. (see https://codesandbox.io/s/react-hook-form-custom-input-i0zn2)
I guess I will have to do as in your exemple (register the field myself and use setValue
). I used to use a workaround for this problem to avoid using those "manual" functions. (Using an registered controlled input type hidden as it seems to work).
<NoSsr><Fragment><Select
isClearable
classes={classes}
className={className}
defaultValue={defaultValue ? selectList.filter(option => option.value === defaultValue)[0] : null}
TextFieldProps={{
...other
}}
shrink={!!value}
endAdornment={endAdornment}
placeholder={''}
noOptionsMessage={() => 'Pas de résultats'}
loadingMessage={() => 'Chargement...'}
options={selectList}
components={components}
onChange={onChangeReactSelect}
/><input type='hidden' name={name} value={value} ref={name ? (inputRef || register) : null}/></Fragment></NoSsr>
I don't find it quite handy, I don't know how you can improve the code to make it more user friendly. But we can definitely make it work for now ;)
Thank you !
Hi @Romcol,
<Select
isClearable
classes={classes}
className={className}
defaultValue={defaultValue ? selectList.filter(option => option.value === defaultValue)[0] : null}
TextFieldProps={{
...other
}}
shrink={!!value}
endAdornment={endAdornment}
placeholder={''}
noOptionsMessage={() => 'Pas de résultats'}
loadingMessage={() => 'Chargement...'}
options={selectList}
components={components}
onChange={onChangeReactSelect}
/>
<input type='hidden' name={name} value={value} ref={name ? (inputRef || register) : null}/>
This example above looks complicted, and i don't know what you try to acheive. Would be nice have more detail so i can assist better.
I would love to make this lib work for every scenario but in reality, it's all about the trade-off. for a custom component, you probably will have to use setValue
, but even controlled input libraries you will have to register the value via some kinda function or use setState
or useState
yourself. I hope you see the value of uncontrolled input when you just can register
and add validation methods. but again it has it's all about pros and cons, as long as you find the pro is far more than the con it's the right lib.
I am still happy to assist your scenario to make it easy for you tho, but perhaps in a separate issue as this issue about why this first keystroke is not working and handle input with value transform.
much appreciated for you to try out the library and giving feedback 👍
cheers
bill
Hi, thanks for replying and for your support !
What I was trying to achieve and what I did achieve is using a custom component such as react-select without the use of setValue
. What I did is use an input type="hidden" which is registered. In my example I'm using a global custom component for text fields but don't worry.
Instead of using setValue
we can just use <input type='hidden' name={name} value={value} ref={inputRef}/>
with name, value and inputRef
as props. (e.g name="resource" inputRef={register({ required: 'Required resource' })}
and value is the current value. (See "Material UI Select with Hidden" https://codesandbox.io/s/react-hook-form-custom-input-i0zn2).
What I thought could be improved is permit control of inputs in custom components when the ref is actually forwarded to an input. (Such as the TextField component in Material UI). But we can do without.
Anyways, cheers !
Hi @Romcol,
Thanks for the reply. I see what you try to achieve now. 👍
I would love to make this lib works better for you and others, so feel free to provide suggestions or PR to improve. ❤️ Feel free to ask questions or leave issues in the near future too.
Have a nice day :)
Thanks
Bill
react hook form leverages uncontrolled input, so you just need to change the value into defaultValue :)
Oh man I just spent the better part of a day trying to figure this out. So glad this was posted here.
@bluebill1049 - I am running into this Issue again when using the MUI Autocomplete component - even with a defaultValue
set on the component. Any idea why this might be happening?
Here is the input in question:
const countries = require('country-data').countries.all
function DeeplyNestedForm(props: Props) {
const {errors, register} = useFormContext() // <-- Using <FormContext> at a higher level.
// ...
<Autocomplete
options={countries.map(country => ({
label: country.name,
value: country.alpha2,
}))}
onChange={(e, value) => props.onChange({
target: {
name: 'addrCountryCode',
value: value.value ? value.value : undefined,
},
})}
defaultValue={ // <-- Using defaultValue on Autocomplete.
props.addrCountryCode ? countries
.filter(country => country.alpha2 === props.addrCountryCode)
.map(country => ({
label: country.name,
value: country.alpha2,
}))[0] : undefined
}
getOptionLabel={option => option.label}
renderInput={params => (
<TextField
{...params}
className={classes.input}
error={!!errors.addrCountryCode}
helperText={
!!errors.addrCountryCode &&
validationMessages.addrCountryCode[errors.addrCountryCode.type]
}
id='addrCountryCode'
inputRef={
register({
required: true,
})
}
label={`${t('glossary:selectCountry')} *`}
name='addrCountryCode'
type='text'
variant='outlined'
inputProps={{
...params.inputProps,
autoComplete: 'disabled',
style: {padding: '0.1rem'},
}}
/>
)}
/>
// ...
}
try to use value instead of default value, let me know if that works for you.
@bluebill1049 - does not work with value. Runs into the same issue unfortunately.
can you provide a codesandbox for your issue? @andrewjrhill
I am beyond confused now because my codesandbox reproduction is working as expected on keyDown
.
https://codesandbox.io/s/musing-darwin-z883r
I'll keep digging at it to try and figure out what's going wrong on the app implementation.
oh strange... i will take a look at it soon, try to fix one of the issue with TS. i will follow you up tho.
@bluebill1049 - I noticed that the dependency version of react-hook-form
that came down on Codesandbox differed from what I had installed in my project.
I updated from v3.23.17
to v3.28.13
and the issue is now resolved on my side.
If anything, hopefully that codesandbox can be used as an example of a possible way to use a deeply nested MUI Autocomplete with react-hook-form.
Thanks for the assist. I really am loving the library you built.
@andrewjrhill I am really glad to hear that! I love problem-solving, building this library and support people around the world is like a dream come true. Thank you for your support and complement as well.
I was experiencing the same issue after focus on an input marked with error, the fix was to start using defaultValue
instead of value
.
react-hook-form
version: 5.6.0
@alejandrotoro do you have a codesandbox on this? are you using Controller? are you using defaultValue with onChange?
Hi @bluebill1049 and btw, thank you! react-hook-form
is really amazing!
And yes I'm using defaultValue
with onChange
, but as I said, I solved my problem using defaultValue
instead of value
.
I just wanted to write a comment for other people that come to this post looking for how to solve the same issue.
Hi all.
I'm getting the same issue when using a normal input field but only once the form is validated and is invalid.
Here is the sandbox to help, i'm sure its something I'm doing wrong.
https://codesandbox.io/s/react-hook-form-error-0xhe3
The only thing I can see is that the onChange event doesn't fire on first keypress.
Thanks for your help!
@kurt-hardy https://react-hook-form.com/faqs#Whyisfirstkeystrokeisnotworking take a look there.
Oh jeez, I wish i'd have seen that. Thank you.
I did try default value but I didn't remove value. 😂
all good @kurt-hardy 👍
We just encountered this issue and created a codesandbox for it.
https://codesandbox.io/s/pedantic-wescoff-k7suq?file=/src/App.js
We used:
const { register, formState: { dirty } } = useForm();
and we noticed that we can fix the problem by simply removing {dirty}
Does that make sense?
We just encountered this issue and created a codesandbox for it.
https://codesandbox.io/s/pedantic-wescoff-k7suq?file=/src/App.jsWe used:
const { register, formState: { dirty } } = useForm();
and we noticed that we can fix the problem by simply removing {dirty}
Does that make sense?
no, that's incorrect. Take a look here: https://codesandbox.io/s/react-hook-form-controller-079xx
Hi,
I am using react-hook-form v:6.3.2 with material UI. My jsx element look like this:
<MDBInput className="white-text" label="Your email" type="email" name="email"
placeholder="Email ID"
onChange={handleUserFieldChange}
inputRef={register({
required: { value: true, message: "Email is required" },
pattern: { value: /^([a-zA-Z0-9_\-.]+)@([a-zA-Z0-9_\-.]+)\.([a-zA-Z]{2,5})$/i, message: "Enter a valid Email ID" }
})}>
{errors.email && (
<span className="red-text">{errors.email.message}</span>
)}
</MDBInput>
I am using only an onChange event listener but not using value or defaultValue. Still I am facing the issue.
@AbhijeetChowdhury92 did you try adding the defaultValue
property?
Yes @alejandrotoro , but no luck still.
@AbhijeetChowdhury92 wrong usage.
Take a look at the doc:
https://react-hook-form.com/api#Controller
there is a codesandbox example as well:
https://codesandbox.io/s/react-hook-form-v6-controller-qsd8r
Most helpful comment
@andrewjrhill I am really glad to hear that! I love problem-solving, building this library and support people around the world is like a dream come true. Thank you for your support and complement as well.