Reputation: 402
Trying to use Formik and Yup with Antd but stuck at simple error. I got code listed below. Email field (Input) works fine but, when I change Age field (InputNumber) I got error in formik: "TypeError: Cannot read property 'type' of undefined". Сan't understand why its happend and where should I find this undefined type property. Tryed to set type=number for "age" (InputNumber) its not help - i got the same error. Can anyone know how to use Formik and Yup with antd, and can help?
import React from 'react';
import * as ReactDOM from 'react-dom';
import { Form, Input, InputNumber, Button } from 'antd';
import { withFormik, FormikErrors, FormikProps } from "formik";
import * as Yup from 'yup';
class RegForm extends React.Component {
constructor(props) {
super(props);
}
render(){
const { values, handleChange, handleBlur, handleSubmit, touched, errors } = this.props;
return(
<Form onSubmit={handleSubmit}>
<Form.Item
help={touched.email && errors.email ? errors.email : ""}
validateStatus={touched.email && errors.email ? "error" : "success"}
label="E-mail"
name="email"
>
<Input
placeholder="E-mail"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
/>
</Form.Item>
<Form.Item
help={touched.age && errors.age ? errors.age : ""}
validateStatus={touched.age && errors.age ? "error" : "success"}
label="Age"
name="age"
>
<InputNumber
value={values.age}
onChange={handleChange}
onBlur={handleBlur}
/>
</Form.Item>
<Form.Item>
<Button
type="primary"
htmlType="submit"
className="form-submit-button"
>
Send
</Button>
</Form.Item>
</Form>
);
}
}
const vSchema = Yup.object().shape({
email: Yup.string()
.email('Not valid mail')
.required('Required'),
age: Yup.number()
.test({
message:'From 18 to 65',
test: value => {
return (value >= 18 && value <=65)
},
})
.required('Required')
});
const FormView = withFormik({
vSchema,
mapPropsToValues: () => ({ email: '', age: ''}),
handleSubmit: async (values, { props, setErrors }) => {
const errors = await props.submit(values);
if (errors) {
setErrors(errors);
}
}
})(RegForm);
ReactDOM.render(<FormView />, document.getElementById('root'));
Upvotes: 1
Views: 5541
Reputation: 121
Looks like an Ant Design quirk, and in deed it works when you do the workaround onChange={value => setFieldValue('age', value)}
.
To make your life easier when using Formik and Ant Design you can try out formik-antd. This library takes away the need to write all the bindings, and generally works great IMO.
Upvotes: 1