G
G
ghrtghrtq2020-04-15 19:25:30
React
ghrtghrtq, 2020-04-15 19:25:30

How to convert a functional component into a class component if I have these three lines?

I have a functional component SignupForm. But I need to convert it into a class component.

I know that the class component should have:
- a line similar to this: class SignupForm extends React.Component
- method render()

But I also have:
1) const history = useHistory();
2) history.push("/home"); in the method - onSubmit
3)

const {handleSubmit, values, handleChange, errors, handleBlur} = useFormik({ /..  });


And I don't know how to convert a functional component into a class component because of these three lines. How to do it?

Small part of SignupForm.js:

const SignupForm = () => {

    const history = useHistory();
    const {handleSubmit, values, handleChange, errors, handleBlur, isSubmitting, setSubmitting} = useFormik({  
      initialValues: {
      /........
      },
        validateOnBlur: false,
        /........
        validationSchema: yup.object().shape({ 
          username: yup.string()      
           .required('This field is required'),
       /........
      }),  
     onSubmit: async (formValues) => {
          try {
              const res = await apiFunction('", {
              /........
              });
              if(){              
            /.......
              } else {
                
                 history.push("/home");
             }
          } catch(e) { 
              /........
          } 
       },  
    });

   return (

      <form onSubmit={handleSubmit}>   
     <SignupInput
         /.......
         inputProps={{
           name:'username',
           value: values.username,
           onBlur: handleBlur,
           /.......
            }} error={errors.username} />
      <button type="submit" disabled={isSubmitting}>Submit Form</button>
     </form>
   );
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wondermarin, 2020-04-15
@ghrtghrtq

Why do you need to remake the component into a class one? Unclear.
1. useHistory can be replaced with:

import { withRouter } from "react-router-dom";

class MyComponent extends React.Component {
  ...

  render() {
    const { history } = this.props;
    ...
  }
}

export default withRouter(MyComponent);

2. history.push- do not need to be replaced.
3. Formik has HOC withFormik() https://jaredpalmer.com/formik/docs/api/withFormik.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question