1
votes

Trying to use react-hook-form FormContext.

I'm supplying deafultValues object in useForm hook. But couldn't manage to populate my component, simple textfield, with the default value in by Bottom.tsx component.

sandbox

1
if defaultValues is coming async, you can use reset at useEffectBill

1 Answers

2
votes

Not sure if you got this working, but I was able to get it working by spreading the methods and using Controller for both TextFields. Also, you were importing control from RHF but it's actually returned from useFormContext()

import React from "react";
import Bottom from "./Bottom";
import { Grid } from "@material-ui/core";
import { useForm, FormContext } from "react-hook-form";

const App = () => {
  const defaultValues = {
    car: "AUDI",
    city: "Tokyo"
  };
  const { ...methods } = useForm({ defaultValues });

  return (
    <FormContext {...methods}>
      <Grid container direction="column">
        <Grid item>
          <Bottom />
        </Grid>
      </Grid>
    </FormContext>
  );
};

export default App;
import React from "react";
import { TextField } from "@material-ui/core";
import { useFormContext, Controller } from "react-hook-form";

interface BottomProps {}

const Bottom: React.FunctionComponent<BottomProps> = (props: BottomProps) => {
  const { register, control } = useFormContext();
  return (
    <>
      <Controller
        name="city"
        control={control}
        as={
          <TextField
            ref={register}
            style={{ margin: 20 }}
            variant="outlined"
            size="small"
            label="City"
          />
        }
      />
      <Controller
        name="car"
        control={control}
        as={
          <TextField
            ref={register}
            style={{ margin: 20 }}
            variant="outlined"
            size="small"
            label="Car"
          />
        }
      />
    </>
  );
};

export default Bottom;

https://codesandbox.io/s/dreamy-goldwasser-so349?file=/src/App.tsx