3

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.

thammada.ts
  • 5,065
  • 2
  • 22
  • 33
Nnp
  • 1,813
  • 7
  • 36
  • 62

2 Answers2

6

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.

n1stre
  • 5,856
  • 4
  • 20
  • 41
0

Here you go :

First : we need the input box, with name that can generate the texted output

name="localAddress[0][street1]"
name="localAddress[0][street2]"
name="localAddress[0][city]"

name="localAddress[1][street1]"
name="localAddress[1][street2]"
name="localAddress[1][city]"


// to generate the name you can do something like this
<Input
    type="text"
    name={`localAddress[${i}][${columns[j]["accessor"]}]`}
    placeholder={columns[j]["accessor"]}
    innerRef={methods.register}
/>

Second : we need access to methods

// pass it from props
<Table1
    name="tag"
    ref={methods.register}
    columns={columns}
    data={localAddress}
    methods = {methods} // <---- Pass HERE
/>

// access it via props
export const Table1 = React.forwardRef(({ columns, data, methods }, ref) => { 

WORKING DEMO : (for output you can check the console)

Edit #SO-hook-forms-solved

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122