/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

  1. import { useFormik } from "formik";
  2. import { useEffect, useState } from "react";
  3. const roles = ["host", "user"];
  4. const initialRole = "user";
  5. const toggleRole = (role) => (role === "host" ? "user" : "host");
  6. const coreFormFields = ["email", "password", "phone"];
  7. const hostFormFields = coreFormFields.concat(["country", "description"]);
  8. const userFormFields = coreFormFields.concat(["birth", "contact"]);
  9. const createRoleController = (role) => {
  10. const roleProgramData = {
  11. role,
  12. formFields: role === "host" ? hostFormFields : userFormFields,
  13. google: null,
  14. facebook: null,
  15. };
  16. return {
  17. ...roleProgramData,
  18. getValuesForForm: Object.fromEntries(
  19. roleProgramData.formFields.map((field) => [field, ""])
  20. ),
  21. getComponentsForForm: (formik) =>
  22. createComponentsForForm({
  23. formik,
  24. formFields: roleProgramData.formFields,
  25. }),
  26. };
  27. };
  28. const createComponentsForForm = ({ formik, formFields }) => {
  29. return formFields.map((field) => {
  30. return (
  31. <input
  32. name={field}
  33. key={field}
  34. onChange={formik.handleChange}
  35. placeholder={field}
  36. value={formik.values[field]}
  37. />
  38. );
  39. });
  40. };
  41. const checkRequiredFields = (requiredFields) => {
  42. return !requiredFields.find((field) => field.lenght < 1);
  43. };
  44. const checkEmail = (email) => {
  45. email.match(
  46. /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
  47. );
  48. };
  49. const checkPassword = (password) => {
  50. return (
  51. (password.length > 0 && password.match(/[A-Z]/)) ||
  52. password.match(/\d/) ||
  53. password.match(/[!$&]/) ||
  54. password.length >= 8
  55. );
  56. };
  57. let roleController = createRoleController(initialRole);
  58. export default () => {
  59. const [role, setRole] = useState(initialRole);
  60. const handleToggleRole = () => {
  61. setRole(toggleRole(role));
  62. };
  63. // const [fieldError, setFieldError] = useState(null);
  64. const formik = useFormik({
  65. initialValues: roleController.getValuesForForm,
  66. onSubmit: (values) => console.log(values),
  67. });
  68. useEffect(() => {
  69. roleController = createRoleController(role);
  70. formik.setValues(roleController.getValuesForForm);
  71. }, [role]);
  72. return (
  73. <>
  74. <form onSubmit={formik.handleSubmit}>
  75. {roleController.getComponentsForForm(formik)}
  76. <button type="submit">Sign up</button>
  77. </form>
  78. <button onClick={handleToggleRole}>{toggleRole(role)}</button>
  79. </>
  80. );
  81. };