Change Formik to react-hook-form v7

Viewed 14

I am refactoring a Formik form to react-hook-form v7. The Formik form has this structure:

<FormikProvider value={form}>
 <Form>
 <Field
    component={FighterInput}
    fighterAvailability={fighterAvailabilityStatus}
 />
 <StandardButton
  type="submit"
 >
 </StandardButton>
</Form>
</FormikProvider>

The FighterInput component is a component which has an input field and a function that renders a div based on fighter availability.

I need to get the typed in value character by character because a useEffect triggers other functions so I need to use react-hook-form watch or something else that let's me grab every character that is typed in to the {FighterInput} component, this is currently achieved with Formiks context values, but I need to do this in react-hook-form.

I've been able to get the value using watch with the following approach:

const fighter = watch('fighterInput');

<form>
      <input {...register("fighterInput")} />
</form>

But this is not using the {FighterInput} component. The {FighterInput} component accepts props and returns an an input field. It also has some functions that renders a div based on conditionals set in the useEffect in the main component where I want to use react-hook-form and import {FighterInput}

How can I transform the Formik form with the above structure to achieve the same thing using react-hook-form v7 and render the {FighterInput} component while being able to grab every character on-the-fly as it is being typed into the input of {FighterInput} ?

<Controller
  control={control}
  name="test"
  render={({
    field: { onChange, onBlur, value, name, ref },
    fieldState: { invalid, isTouched, isDirty, error },
    formState,
  }) => (
    <FighterInput
      onChange={onChange} // send value to hook form
      checked={value}
      inputRef={ref}
      {...register("fighterInput")} // not working

    />
  )}
/>

In addition to being able to watch the input, I need to be able to access form values in my FighterInput component as well and wondering how I can do that, am I supposed to use react-hook-forms useFormContext or FormProvider?

0 Answers
Related