Title rewritten to: "Invalid Hook call in react-hook-form"
P粉752479467
P粉752479467 2023-08-31 11:51:28
0
1
573
<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>
P粉752479467
P粉752479467

reply all(1)
P粉567112391

Define the NumberInput component separately, and then use Controller packaging directly in the form:

// NumberInput.js
export const NumberInput = ({ value, onChange, ...rest }) => {
  const handleChange = (e) => {
    onChange(Number(e.target.value));
  };
 
  return (
    <input
      type="number"
      min={0}
      onChange={handleChange}
      value={value}
      {...rest}
    />
  );
};

Then within the component that calls useForm:

<Controller
  name='number'
  control={control}
  render={({ field: { ref, ...field } }) => (
    <NumberInput {...field} type="number" />
  )}
/>

You can find more information in this article.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template