Title rewritten to: "Invalid Hook call in react-hook-form"
P粉752479467
2023-08-31 11:51:28
<p>I'm new to react hook forms, so it might be a simple question. I just discovered that the Controller cannot use value as a number. This annoyed me a lot, but eventually I found the solution in github issue #8068, described as follows: Set up an onChange function, like this: </p>
<pre class="brush:php;toolbar:false;"><Controller
- rules={{ valueAsNumber: true }}
render={({ field }) => (
<input
- onChange={field.onChange}
onChange={(event) => field.onChange( event.target.value)}
type="number"
/>
)}
/></pre>
<p>So I modified it a little and got the following code: </p>
<pre class="brush:php;toolbar:false;">import React, { ChangeEvent } from 'react'
import { Controller } from 'react-hook-form'
import { getPlaceholder } from './getPlaceholder'
import { IInput } from './types'
const NumberInput: React.FC<IInput> = ({ control, name, ...props }) => {
const placeholder = getPlaceholder({ type: "number" });
const numericalOnChange = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.value === '') return null;
return event.target.value;
}
return (
<Controller
control={control}
name={name}
render={({ field: { onChange, ...field } }) => (
<input
{...props}
{...field}
type="number"
placeholder={placeholder}
onChange={(event) => {
const value = numericalOnChange(event)
onChange(value)
}}
className="h-[20px] pl-[4px] py-[8px] bg-transparent border-b
border-b-[#646464] focus:border-b-[#3898EC] text-[13px]
text-[#F00] placeholder-[#646464] outline-none m-1 w-full"
/>
)}
/>
)
}
export default NumberInput</pre>
<p>This should work in theory, but in practice will give an Invalid Hook Call Error. </p>
Define the
NumberInput
component separately, and then useController
packaging directly in the form:Then within the component that calls
useForm
:You can find more information in this article.