Formik - rkaku/formik-material-ui GitHub Wiki
- component?: React.ComponentType<FormikProps>
- render: (props: FormikProps) => ReactNode
- children?: React.ReactNode | (props: FormikProps) => ReactNode
- enableReinitialize?: boolean
- isInitialValid?: boolean
- initialErrors?: FormikErrors
- initialStatus?: any
- initialTouched?: FormikTouched
- initialValues: Values
- onReset?: (values: Values, formikBag: FormikBag) => void
- onSubmit: (values: Values, formikBag: FormikBag) => void
- validate?: (values: Values) => FormikErrors | Promise
- validateOnBlur?: boolean
- validateOnChange?: boolean
- validateOnMount?: boolean
- validationSchema?: Schema | (() => Schema)
import React from 'react';
import { Formik } from 'formik';
const BasicExample = () => (
<div>
<h1>My Form</h1>
<Formik
initialValues={{ name: 'jared' }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
>
{props => (
<form onSubmit={props.handleSubmit}>
<input
type="text"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.name}
name="name"
/>
{props.errors.name && <div id="feedback">{props.errors.name}</div>}
<button type="submit">Submit</button>
</form>
)}
</Formik>
</div>
);<button onClick={handleReset}>...</button><Formik component={ContactForm} />;
const ContactForm = ({
handleSubmit,
handleChange,
handleBlur,
values,
errors,
}) => (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
name="name"
/>
{errors.name && <div>{errors.name}</div>}
<button type="submit">Submit</button>
</form>
);Deprecated in 2.x
<Formik children={props => <ContactForm {...props} />} />
// or...
<Formik>
{({ handleSubmit, handleChange, handleBlur, values, errors }) => (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
name="name"
/>
{errors.name &&
<div>
{errors.name}
</div>}
<button type="submit">Submit</button>
</form>
)}
</Formik>// Synchronous validation
const validate = values => {
const errors = {};
if (!values.email) {
errors.email = 'Required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address';
}
//...
return errors;
};// Async Validation
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const validate = values => {
return sleep(2000).then(() => {
const errors = {};
if (['admin', 'null', 'god'].includes(values.username)) {
errors.username = 'Nice try';
}
// ...
return errors;
});
};