I have a form with multiple components in it (with each being either a functional or a class based component) containing multiple input fields or radio buttons. When I submit the form I either want to submit the fields that are nested into components along with the form data or I should be able to extract the fields data and then submit them (not sure which approach would be the best and why?). How can I achieve this?
Code :
import React from "react";
import { useForm } from "react-hook-form";
export default function TestComponent() {
const { register, handleSubmit, errors } = useForm();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="name">Name</label>
<input type="text" id="name" name="name" ref={register({ required: true, maxLength: 30 })} />
{errors.name && errors.name.type === "required" && <span>This is required</span>}
{errors.name && errors.name.type === "maxLength" && <span>Max length exceeded</span> }
<NestedComponent1 />
<NestedComponent2 />
<input type="submit" />
</form>
);
}
function NestedComponent1() {
return (
<div>
<input type="text" id="nested-name" name="nestedName" />
<input type="text" id="nested-name2" name="nestedName2" />
<input type="text" id="nested-name3" name="nestedName3" />
</div>
);
}
function NestedComponent2() {
return (
<div>
<input type="text" id="nested-comp2-name" name="nestedcomp2Name" />
<input type="text" id="nested-comp2-name2" name="nestedcomp2Name2" />
<input type="text" id="nested-comp2-name3 name="nestedcomp2Name3" />
</div>
);
}