Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-table v7 within react-hook-form

i am working on a complex react form where it has few controlled inputs along with grid/table. currently i am using react-hook-form for validation.
here is my mockup. idea here is show grid as required until user adds some data. user can add/remove data by clicking "+" or "-" buttons.

Mockup
when i submit here is what i see in submitted data

{
  "fname": "sasa",
  "lname": "asasasa"
} 

here is the expected output

{
  "fname": "sasa",
  "lname": "asasasa",
  "localAddress":[
    {
      "street1":"street1",
      "street2":"street2",
      "city":"city"
    },
    {
      "street1":"street2",
      "street2":"street2",
      "city":"city"
    }
  ]
} 



here is my codesanbox
Codesanbox

not sure how can i integrate react-table (or any table component) with react-hook-form (or any react form). building a form using "react-table" is a must for me.

appreciate any help.

like image 762
Nnp Avatar asked Mar 05 '26 15:03

Nnp


1 Answers

As mentioned in the get-started docs in the "Work with UI library" section:

Option 3: we can set up a custom register using the useEffect Hook and update the value via setValue.

So here's what needs to be done in your case:

export default function App() {
  const { register, handleSubmit, setValue } = useForm();
  // ... 

  React.useEffect(() => {
    register({ name: "localaddress" });
  }, [register]);

  const addLocalAddress = function() {
    // ... 
    setValue("localaddress", d);
    setLocalAddress(d);
  };

  // ... 
}

And with this in place you need to get rid of Controller by replacing this:

<Controller
  name="tag"
  control={methods.control}
  as={
    <Table1
      name="tag"
      ref={methods.register}
      columns={columns}
      data={localAddress}
      {...methods}
    />
  }
/>;

with this:

<Table1 columns={columns} data={localAddress} />

That should be it. And of course the sandbox.

like image 70
streletss Avatar answered Mar 07 '26 05:03

streletss