/src/components/Registration.js
https://gitlab.com/vladimirdemonow/test-login · JavaScript · 92 lines · 80 code · 11 blank · 1 comment · 1 complexity · 411e7ecdc1e325fb2733372656cd5635 MD5 · raw file
- import { useFormik } from "formik";
- import { useEffect, useState } from "react";
- const roles = ["host", "user"];
- const initialRole = "user";
- const toggleRole = (role) => (role === "host" ? "user" : "host");
- const coreFormFields = ["email", "password", "phone"];
- const hostFormFields = coreFormFields.concat(["country", "description"]);
- const userFormFields = coreFormFields.concat(["birth", "contact"]);
- const createRoleController = (role) => {
- const roleProgramData = {
- role,
- formFields: role === "host" ? hostFormFields : userFormFields,
- google: null,
- facebook: null,
- };
- return {
- ...roleProgramData,
- getValuesForForm: Object.fromEntries(
- roleProgramData.formFields.map((field) => [field, ""])
- ),
- getComponentsForForm: (formik) =>
- createComponentsForForm({
- formik,
- formFields: roleProgramData.formFields,
- }),
- };
- };
- const createComponentsForForm = ({ formik, formFields }) => {
- return formFields.map((field) => {
- return (
- <input
- name={field}
- key={field}
- onChange={formik.handleChange}
- placeholder={field}
- value={formik.values[field]}
- />
- );
- });
- };
- const checkRequiredFields = (requiredFields) => {
- return !requiredFields.find((field) => field.lenght < 1);
- };
- const checkEmail = (email) => {
- email.match(
- /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
- );
- };
- const checkPassword = (password) => {
- return (
- (password.length > 0 && password.match(/[A-Z]/)) ||
- password.match(/\d/) ||
- password.match(/[!$&]/) ||
- password.length >= 8
- );
- };
- let roleController = createRoleController(initialRole);
- export default () => {
- const [role, setRole] = useState(initialRole);
- const handleToggleRole = () => {
- setRole(toggleRole(role));
- };
- // const [fieldError, setFieldError] = useState(null);
- const formik = useFormik({
- initialValues: roleController.getValuesForForm,
- onSubmit: (values) => console.log(values),
- });
- useEffect(() => {
- roleController = createRoleController(role);
- formik.setValues(roleController.getValuesForForm);
- }, [role]);
- return (
- <>
- <form onSubmit={formik.handleSubmit}>
- {roleController.getComponentsForForm(formik)}
- <button type="submit">Sign up</button>
- </form>
- <button onClick={handleToggleRole}>{toggleRole(role)}</button>
- </>
- );
- };