Answer the question
In order to leave comments, you need to log in
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({ /.. });
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
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);
history.push
- do not need to be replaced. withFormik()
https://jaredpalmer.com/formik/docs/api/withFormik.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question