简体   繁体   中英

Refactoring almost identical components, formik react

I have two identical components, and only few differences (one). There are two many repetitive code and boilerplate, but I am unsure how to refactor this so that I only need to supply a config probably.

LoginPage.js

import React from 'react';
import { Link } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import { Formik, FastField, Form, ErrorMessage } from 'formik';

import PropTypes from 'prop-types';
import { FormDebug } from 'utils/FormDebug';
import { LoginValidationSchema } from 'validations/AuthValidationSchema';

function LoginPage({ username, onChangeUsername, onSubmitForm }) {
  return (
    <div>
      <Helmet>
        <title>Login</title>
      </Helmet>
      <Formik
        initialValues={{ username, password: '' }}
        validationSchema={LoginValidationSchema}
        onSubmit={onSubmitForm}
        render={({ isSubmitting, isValid, handleChange }) => (
          <Form>
            <FastField
              type="text"
              name="username"
              render={({ field }) => (
                <input
                  {...field}
                  onChange={e => {
                    handleChange(e);
                    onChangeUsername(e);
                  }}
                />
              )}
            />
            <ErrorMessage name="username" component="div" aria-live="polite" />
            <FastField type="password" name="password" />
            <ErrorMessage name="password" component="div" aria-live="polite" />
            <button type="submit" disabled={isSubmitting || !isValid}>
              Login
            </button>
            <FormDebug />
          </Form>
        )}
      />
      <Link to="/auth/forgot_password">Forgot Password</Link>
    </div>
  );
}

LoginPage.propTypes = {
  username: PropTypes.string,
  onSubmitForm: PropTypes.func.isRequired,
  onChangeUsername: PropTypes.func.isRequired,
};

export default LoginPage;

ForgotPasswordPage.js

import React from 'react';
import { Helmet } from 'react-helmet';
import { Formik, FastField, Form, ErrorMessage } from 'formik';

import PropTypes from 'prop-types';
import { FormDebug } from 'utils/FormDebug';
import { ForgotPasswordValidationSchema } from 'validations/AuthValidationSchema';

function ForgotPasswordPage({ username, onChangeUsername, onSubmitForm }) {
  return (
    <div>
      <Helmet>
        <title>Forgot Password</title>
      </Helmet>
      <Formik
        initialValues={{ username }}
        validationSchema={ForgotPasswordValidationSchema}
        onSubmit={onSubmitForm}
        render={({ isSubmitting, isValid, handleChange }) => (
          <Form>
            <FastField
              type="text"
              name="username"
              render={({ field }) => (
                <input
                  {...field}
                  onChange={e => {
                    handleChange(e);
                    onChangeUsername(e);
                  }}
                />
              )}
            />
            <ErrorMessage name="username" component="div" aria-live="polite" />
            <FormDebug />
            <button type="submit" disabled={isSubmitting || !isValid}>
              Reset Password
            </button>
          </Form>
        )}
      />
    </div>
  );
}

ForgotPasswordPage.propTypes = {
  username: PropTypes.string,
  onSubmitForm: PropTypes.func.isRequired,
  onChangeUsername: PropTypes.func.isRequired,
};

export default ForgotPasswordPage;

How to you refactor this, if you were me.

I am thinking HOC., but I am unsure how to call pass the "children" which is different

Apologies if you're not looking for a general answer, but I don't think you'll improve maintainability by generalising what may just be seemingly correlated components. I expect these components will drift further apart as you mature your application, eg by adding social login, option to 'remember me', captchas, option for retrieving both username and password by email, different handling of an unknown username when retrieving password vs signing in, etc. Also, this is a part of your component you really don't want to get wrong, so KISS and all. Finally, consider if there really is a third use case for such a semi-generalised login-or-retrieve-password form component.

Still, minor improvement could be made by eg creating a reusable UsernameField component, the usage of which will be simple and consistent to both cases. Also consider a withValidation HOC adding an error message to a field. If you really want to stretch it, you could have a withSubmit HOC for Formik, passing all props to Formik, rendering children (which you would pass handleChange prop) and a submit button. I assume form itself uses context to pass state to ErrorMessage and FastField.

I may be missing some complexity not stated here, but this looks as simple as creating a generic Functional Component that accepts a couple more passed-in properties. I did a diff and you would only need to add 'title', 'buttonText', and, if you like, 'type' to your props, for sure. You could also send initialValues object as a prop, instead of deriving it from 'type'.

I mean, did you try the following?

import React from 'react';
import { Link } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import { Formik, FastField, Form, ErrorMessage } from 'formik';

import PropTypes from 'prop-types';
import { FormDebug } from 'utils/FormDebug';
import * as schema from 'validations/AuthValidationSchema';

function AuthPage({ buttonText, initialValues, title, type, username,
                    onChangeUsername, onSubmitForm }) {
  const authSchema = type === 'login' 
        ? schema.LoginValidationSchema 
        : schema.ForgotPasswordValidationSchema;

  return (
    <div>
      <Helmet>
        <title>{title}</title>
      </Helmet>
      <Formik
        initialValues={initialValues}
        validationSchema={authSchema}
        onSubmit={onSubmitForm}
        render={({ isSubmitting, isValid, handleChange }) => (
          <Form>
            <FastField
              type="text"
              name="username"
              render={({ field }) => (
                <input
                  {...field}
                  onChange={e => {
                    handleChange(e);
                    onChangeUsername(e);
                  }}
                />
              )}
            />
            <ErrorMessage name="username" component="div" aria-live="polite" />
            {type === 'forgot' &&
              <FastField type="password" name="password" />
              <ErrorMessage name="password" component="div" aria-live="polite" />
            }
            <button type="submit" disabled={isSubmitting || !isValid}>
              {buttonText}
            </button>
            <FormDebug />
          </Form>
        )}
      />
      <Link to="/auth/forgot_password">Forgot Password</Link>
    </div>
  );
}

AuthPage.propTypes = {
  buttonText: PropTypes.string,
  initialValues: PropTypes.object,
  title: PropTypes.string,
  type: PropTypes.oneOf(['login', 'forgot'])
  username: PropTypes.string,
  onSubmitForm: PropTypes.func.isRequired,
  onChangeUsername: PropTypes.func.isRequired,
};

export default AuthPage;

(Only thing I can't remember is whether the conditional render of password field and its ErrorMessage needs to be wrapped in a div or not to make them one element)

If you don't want to pass in initial values:

  const initialVals = type === 'login'
        ? { username, password: ''}
        : { username }
  ...
  initialValues={initialVals}

and remove it from propTypes

Only other thing I'm not sure of is why FormDebug is placed differently in the two versions. I've left it after the button.

Those two pages have separate concerns, so I wouldn't suggest pulling logic that can be used for both cases as that tends to add complexity by moving code further apart even if it does remove a few duplicate lines. In this case a good strategy may be to think of things that you reuse within components.

For example you can wrap the formik component in your own wrapper and then wrap for example an input component that works with your new form. A good exercise in reducing boiler plate could be to aim for some variant of this end result

<CoolForm 
  initialValues={{ username, password: '' }}
  validationSchema={LoginValidationSchema}
>
  <CoolFormInputWithError someProps={{howeverYou: 'want to design this'}}>
  <CoolFormInputWithError someProps={{howeverYou: 'want to design this'}}>
  <CoolFormSubmit>
    Login
  </CoolFormSubmit>
  <FormDebug />
</CoolForm>

That's just an idea, but the nice thing about this strategy is that if you want to refactor formik out for whatever reason, its really simple because all your code now is wrapped in CoolForm components, so you only end up changing the implementation of your own components, although that benefit in this case is very small.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM