Use formik with context/hooks instead of render-props
Note that this feature is available in formik >= 2.0
Usually when you’re creating forms using formik
you access formik props using render-prop pattern
export function MyForm() {
return (
<Formik
initialValues={{ /* something here */ }}
onSubmit={(values, actions) => {/* handler here */}}
>
{(formikProps) => (
<form onSubmit={formikProps.handleSubmit}>
<MyInputComponent value={formikProps.values.name} />
</form>
)}
</Formik>
)
}
Instead you can use formik as context provider (which it is under the hood actually) and use useFormikContext()
hook or FormikConsumer
component to consume provided form state.
Example below:
export function MyFormContainer() {
return (
<Formik
{/* Under the hood Formik uses Context Provider */}
initialValues={{ /* something here */}}
onSubmit={(values, actions) => { /* handler here */ }}
>
{/* You do not have to use function here! */}
{/* However you can, if you would like to :) */}
<MyForm />
</Formik>
)
}
export function MyForm() {
const { handleSubmit, values } = useFormikContext(); // formikProps
return (
<form onSubmit={handleSubmit}>
<MyInputComponent value={values.name} />
</form>
);
}
This allows us to use formik props deep down in our nested components
without drilling down formikProps
.