Creating Personal Details Subform
In the UserForm.jsx file, add the following validationSchema and initialValues object:
import * as React from "react";
import * as Yup from "yup";
export const userValidationSchema = Yup.object().shape({
firstName: Yup.string()
.max(15, "Must be 15 character or less")
.required("Required"),
lastName: Yup.string()
.max(20, "Must be 20 character or less")
.required("Required"),
password: Yup.string().min(6, "Password has to be longer than 6 characters!"),
passwordConfirm: Yup.string().oneOf(
[Yup.ref("password"), null],
"Passwords must match"
)
});
export const userInitialValues = {
firstName: "",
lastName: "",
password: "",
passwordConfirm: "",
};
Again, we will need this object in the MainForm.jsx file.
Add the following lines to UserForm.jsx file to create the UserForm Component:
import { Row, Col } from "reactstrap";
import TextInput from "./TextInput";
const UserForm = (props) => {
const { handleChange, namespace } = props;
return (
<div>
<h3 className="my-2">User</h3>
<Row>
<Col xs={12} md={6} className="my-2">
<TextInput
type="text"
label="First Name"
name={namespace + ".firstName"}
onChange={handleChange}
placeholder="First Name"
required
/>
</Col>
<Col xs={12} md={6} className="my-2">
<TextInput
type="text"
label="Last Name"
name={namespace + ".lastName"}
onChange={handleChange}
placeholder="Last Name"
required
/>
</Col>
<Col xs={12} className="my-2">
<TextInput
type="password"
label="Password"
name={namespace + ".password"}
onChange={handleChange}
/>
</Col>
<Col xs={12} className="my-2">
<TextInput
label="Confirm Password"
type="password"
name={namespace + ".passwordConfirm"}
onChange={handleChange}
/>
</Col>
</Row>
</div>
);
};
export default UserForm;
We can name the fields whatever we want without worrying about same names of fields because each subform will have their own namespace and formik will reference the fields with their namespace.
We need to connect these 2 subforms in the MainForm to display the fields on the App.
2
