Is there a way I can validate a nested component form item from its parent form when submitting?
Here is an example, I know I could handle both items in the same form and this is not the best way to pass the data from child to parent component (It's just a simple example to illustrate my question). I have a more complex situation than this example..
App.js
import React from "react";
import { FormComponentProps } from "antd/lib/form/Form";
import { Input, Form } from "ant";
import ChildComponent from "./ChildComponent";
function App() {
const [state, setState] = React.useState("");
const [childValue, setChildValue] = React.useState("");
const handleSubmit = e => {
e.preventDefault();
props.form.validateFields((err, values) => {
if (!err) {
console.log(state);
console.log(childValue);
}
});
};
const { getFieldDecorator } = props.form;
return (
<Form onSubmit={handleSubmit}>
<Form.Item
label="Name"
labelAlign="left"
colon={false}
labelCol={{ span: 8 }}
wrapperCol={{ span: 14 }}
required={false}
>
{getFieldDecorator("name", {
rules: [
{
required: true
}
]
})(
<Input
type="text"
name="Name"
onChange={e => setState(e.target.value)}
/>
)}
</Form.Item>
<ChildComponent setChildValue={setChildValue} />
</Form>
);
}
const WrappedApp = Form.create({ name: "App" })(App);
export default WrappedApp;
ChildComponent.js
import React, { useEffect } from "react";
import { Input, Form } from "antd";
function ChildComponent(props) {
const [state, setState] = React.useState("");
useEffect(() => {
props.setChildValue(state);
}, [state]);
const { getFieldDecorator } = props.form;
return (
<Form.Item
label="Last"
labelAlign="left"
colon={false}
labelCol={{ span: 8 }}
wrapperCol={{ span: 14 }}
required={false}
>
{getFieldDecorator("last", {
rules: [
{
required: true
}
]
})(
<Input
type="text"
name="Last"
onChange={e => setState(e.target.value)}
/>
)}
</Form.Item>
);
}
export default ChildComponent;
When I submit the form from App.js, I want to also check the validation of item from the ChildComponent.js. Is there a way I can pass a reference from App.js form to validate the item in ChildComponent?
P.s.
I have tried passing props.form
from App.js to ChildComponent.js. It didn't check the validation for the ChildComponent item.