import React from 'react';
import { Formik, Field } from 'formik';
import {
Checkbox,
Form,
FormControl,
Radio,
Select,
Textarea,
TextInput,
} from '@contentful/f36-forms';
export const FormikForm = () => {
const initialValues = {
textInput: '',
textarea: '',
select: 'Mumbai',
radioGroup: 'apples',
checkboxGroup: ['apples'],
checkbox: false,
};
const validateRequired = (value) => !value;
const onSubmit = (data) => {
console.log(data);
};
return (
<Formik onSubmit={onSubmit} initialValues={initialValues}>
{}
{({ handleSubmit }) => (
<Form onSubmit={handleSubmit}>
{}
<Field name="textInput" validate={validateRequired}>
{
}
{({ field, meta }) => (
<FormControl isInvalid={Boolean(meta.touched && meta.error)}>
<FormControl.Label>Text input</FormControl.Label>
<TextInput {...field} />
{meta.touched && meta.error && (
<FormControl.ValidationMessage>
{meta.error}
</FormControl.ValidationMessage>
)}
</FormControl>
)}
</Field>
{}
<Field name="textarea" validate={validateRequired}>
{({ field, meta }) => (
<FormControl isInvalid={Boolean(meta.touched && meta.error)}>
<FormControl.Label>Textarea</FormControl.Label>
<Textarea {...field} />
{meta.touched && meta.error && (
<FormControl.ValidationMessage>
{meta.error}
</FormControl.ValidationMessage>
)}
</FormControl>
)}
</Field>
{}
<Field name="select">
{}
{({ field }) => (
<FormControl>
{}
<Select {...field}>
<Select.Option value="Cape Town">Cape Town</Select.Option>
<Select.Option value="Mumbai">Mumbai</Select.Option>
<Select.Option value="Rio de Janeiro">
Rio de Janeiro
</Select.Option>
</Select>
</FormControl>
)}
</Field>
{}
<Field name="radioGroup">
{({ field }) => (
<Radio.Group {...field}>
<Radio value="apples">Apples</Radio>
<Radio value="pears">Pears</Radio>
<Radio value="peaches">Peaches</Radio>
</Radio.Group>
)}
</Field>
{}
<Field name="checkboxGroup">
{({ field }) => (
<Checkbox.Group {...field}>
<Checkbox value="apples">Apples</Checkbox>
<Checkbox value="pears">Pears</Checkbox>
<Checkbox value="peaches">Peaches</Checkbox>
</Checkbox.Group>
)}
</Field>
{}
<Field name="checkbox" validate={validateRequired}>
{({ field, meta }) => (
<FormControl
isRequired
isInvalid={Boolean(meta.touched && meta.error)}
>
{}
<Checkbox {...field} defaultChecked={false}>
This checkbox is required
</Checkbox>
{meta.touched && meta.error && (
<FormControl.ValidationMessage>
{meta.error}
</FormControl.ValidationMessage>
)}
</FormControl>
)}
</Field>
<Flex justifyContent="flex-end">
<Button variant="primary" type="submit">
Submit
</Button>
</Flex>
</Form>
)}
</Formik>
);
};