Hi.
I've been working on a simple react based input form with formik.
Especially I'd like to use withFormik() with a class based component as metioned above.
Simply, withFormik doesn't work.
My codes go like this...
class MyForm extends Component {
render() {
return (
<div>
<Formik>
{props => {
const { touched, errors, values } = props;
return (
<Form onSubmit={this.onSubmit}>
<label>NAME</label>
<Field name="userName" />
<br />
{errors.userName && touched.userName && (
<div id="feedback">{errors.userName}</div>
)}
{console.log("values", values)}
{console.log("errors", errors)}
<br />
<label>Cell Phone</label>
<Field name="number" />
<br />
{errors.number && touched.number && (
<div id="feedback">{errors.number}</div>
)}
<br />
<button type="submit">Submit</button>
</Form>
);
}}
</Formik>
</div>
);
}
}
const MyEnhancedForm = withFormik({
mapPropsToValues: () => ({ userName: "" }),
// Custom sync validation
validate: values => {
const errors = {};
if (!values.userName) {
errors.name = "Required";
}
console.log(errors);
return errors;
},
handleSubmit: (values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 1000);
},
displayName: "BasicForm"
})(MyForm);
export default MyEnhancedForm;`
Is it impossible to make withFormik work that way?
I recommend use withFormik, it's more flexible to use inside the methods.
Can you create a codesandbox.io with your code ?
You don鈥檛 need both withFormik and the Formik component. If you use withFormik with a class it will inject the props as this.props.
@jaredpalmer can you provide any snippet to use withFormik with class component ?
@bilalbutt044 https://jaredpalmer.com/formik/docs/api/withFormik
@bilalbutt044 https://jaredpalmer.com/formik/docs/api/withFormik
This does NOT use a class.
@barrychapman here is what I am using:
```typescript
import { withFormik, FormikProps } from 'formik';
interface IFormProps {
formData: MyFormData;
onSubmit: (data: CustomerFormData) => void
}
class MyTestForm extends React.PureComponent
render() {
const { submitCount, isValid, touched, handleChange, handleBlur, values, errors } = this.props;
return (
)
}
export default withFormik
mapPropsToValues: ({ formData }) => formData,
validate: () => undefined,
handleSubmit: (values) => { }
})(MyTestForm)