search

Home  >  Q&A  >  body text

Title rewritten to: "Invalid Hook call in react-hook-form"

<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粉752479467P粉752479467497 days ago602

reply all(1)I'll reply

  • P粉567112391

    P粉5671123912023-09-01 10:51:39

    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.

    reply
    0
  • Cancelreply