Is it possible to trasnform outgoing values with just register and v7 of react-hook-form?
I did this by overwriting the e I pass to onChange however it never becomes the value I set it. 325
const { onChange, ...registration } = props.form.register('foo');
const handleChange = e => {
const value = e.target.value;
const transformedValue = 325;
onChange({
type: e.type,
target: {
name: e.target.name,
type: e.target.type,
value: transformedValue
}
});
};
return <input {...registration} onChange={handleChange} />
The problem here is that no ref can be initialised by your call to register outside the <input /> element.
For the registration of a ref you can either add a custom register, this would give you the possibility to modify the current value of your <input /> element after a change via the setValue method (which is provided by useForm). Or another way would be to share your ref to your <input />.
However, I think that setValueAs should also work well in your case. This will run the provided function before returning your input value. Here is the relevant section from the docs.
<input {...register("foo", { setValueAs: value => `${value} 325` })} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With