In this section, we'll consume the onSubmit form prop in the ContactUs component. The ContactUs component won't manage the submission—it will simply delegate to the ContactUsPage component to handle the submission:
- Let's start by importing ISubmitResult and IValues, and creating a props interface in the ContactUs component for the onSubmit function:
import { Form, ISubmitResult, IValues, minLength, required } from "./Form";
interface IProps {
onSubmit: (values: IValues) => Promise<ISubmitResult>;
}
const ContactUs: React.SFC<IProps> = props => { ... }
- Create a handleSubmit function that will invoke the onSubmit prop:
const ContactUs: React.SFC<IProps> = props => {
const handleSubmit = async (values: IValues): Promise<ISubmitResult> => {
const result = await props.onSubmit(values);
return result;
};
return ( ... );
};
The onSubmit prop is asynchronous, so we need to prefix our function with async and prefix the onSubmit call with await.
- Bind this submit handler in the form onSubmit prop in the JSX:
return (
<Form ... onSubmit={handleSubmit}>
...
</Form>
);
- Let's move on to the ContactUsPage component now. Let's start by creating the submit handler:
private handleSubmit = async (values: IValues): Promise<ISubmitResult> => {
await wait(1000); // simulate asynchronous web API call
return {
errors: {
email: ["Some is wrong with this"]
},
success: false
};
};
In practice, this will probably call a web API. In our example, we wait asynchronously for one second and return a validation error with the email field.
- Let's create the wait function we just referenced:
const wait = (ms: number): Promise<void> => {
return new Promise(resolve => setTimeout(resolve, ms));
};
- Let's wire up the handleSubmit method to the ContactUs onSubmit prop now:
<ContactUs onSubmit={this.handleSubmit} />
- We have referenced IValues and ISubmitResult, so let's import these:
import { ISubmitResult, IValues } from "./Form";
If we go to the Contact Us page in the running app, fill out the form, and click the Submit button, we are informed that there is a problem with the email field, as we would expect:
- Let's change the submit handler in ContactUsPage to return a successful result:
private handleSubmit = async (values: IValues): Promise<ISubmitResult> => {
await wait(1000); // simulate asynchronous web API call
return {
success: true
};
};
Now, if we go to the Contact Us page in the running app again, fill out the form, and click the Submit button, the submission goes through fine and the Submit button is disabled:
So, that's our Contact Us page complete, together with our generic Form and Field components.