Creating Address Subform
We are going to create a subform for address input fields and then another subform for user details and then add them in a combined form with some other fields so as to show you how we can access fields that belong only to the main form.
In the Components folder, create MainForm.jsx, UserForm.jsx and AddressForm.jsx files in this folder.
In AddressForm.jsx, we write the validation schema for the fields present in the form.
import * as React from "react";
import * as Yup from "yup";
export const addressValidationSchema = Yup.object().shape({
state: Yup.string().required("Required"),
country: Yup.string().required("Required"),
zipcode: Yup.string().max(6, "Must be 6 digits or less").required("Required"),
city: Yup.string().required("Required")
});
export const addressInitialValues = {
state: "",
city: "",
country: "",
zipcode: "",
};
We export validationSchema and initialValues because we will require it in the MainForm.jsx file later.
Add the following lines in AddressForm.jsx to create the AddressForm Component:
import { Row, Col } from "reactstrap";
import TextInput from "./TextInput";
const AddressForm = (props) => {
const { handleChange, namespace } = props;
return (
<div>
<h3 className="my-2">Address</h3>
<Row>
<Col xs={12} className="my-2">
<TextInput
type="text"
label="State"
name={namespace + ".state"}
onChange={handleChange}
placeholder="State"
required
/>
</Col>
<Col xs={12} className="my-2">
<TextInput
type="text"
label="City"
name={namespace + ".city"}
onChange={handleChange}
placeholder="City"
required
/>
</Col>
<Col xs={12} className="my-2">
<TextInput
type="text"
label="Country"
name={namespace + ".country"}
onChange={handleChange}
placeholder="Country"
required
/>
</Col>
<Col xs={6} className="my-2">
<TextInput
type="text"
label="Zipcode"
name={namespace + ".zipcode"}
onChange={handleChange}
placeholder="Zipcode"
required
/>
</Col>
</Row>
</div>
);
};
export default AddressForm;
Note: This is just a tutorial on how to create subforms using Formik and React. In a real application, you might want to tighten the validation and keep a dropdown for Country, State and City fields.
Our AddressForm Component is now ready.
2
