Skip to content

Instantly share code, notes, and snippets.

@Landerson352
Created September 5, 2019 16:31
Show Gist options
  • Save Landerson352/cb15ce9f9e360864459f990ea3f55978 to your computer and use it in GitHub Desktop.
Save Landerson352/cb15ce9f9e360864459f990ea3f55978 to your computer and use it in GitHub Desktop.
React Native "Field Group" Component for use w/Formik
import React from 'react';
import { Input } from 'react-native-elements';
import { Field } from 'formik';
import { utils } from '../theme';
import MoneyInput from './MoneyInput';
import PickerSelect from './PickerSelect';
import Text from './Text';
/*
A component for rendering Formik fields with labels and errors.
Example Text Field:
<FieldGroup name="name" label="Name" />
Example Money Field:
<FieldGroup name="amount" label="Amount" type="money" />
Example Picker Field:
<FieldGroup
name="state"
label="State"
type="select"
items={[{ id: 1, label: 'Alabama' }, { id: 2, label: 'Arkansas' }]}
/>
*/
const FieldGroup = ({ label, name, children, type = 'text', ...fieldProps }) => (
<Field name={name}>
{({ field, form }) => {
const componentFieldProps = {};
const fieldOverrideProps = {};
// Map "type" to "Component"
let Component = Input;
if (type === 'money') {
Component = MoneyInput;
} else if (type === 'select') {
Component = PickerSelect;
}
let elements;
if (children) {
elements = children({ field, form });
} else {
// map events depending on component
if (Component === PickerSelect) {
componentFieldProps.onValueChange = (value) => {
form.handleChange(name)(value);
form.handleBlur(name);
};
if (fieldProps.placeholder === false) {
fieldOverrideProps.placeholder = {};
}
} else {
componentFieldProps.onChangeText = form.handleChange(name);
componentFieldProps.onBlur = form.handleBlur(name);
if (!fieldProps.maxLength) {
if (Component === MoneyInput) {
fieldOverrideProps.maxLength = 10; // $99.999.99
} else {
fieldOverrideProps.maxLength = 255;
}
}
}
elements = (
<Component
name={name}
value={field.value}
{...componentFieldProps}
{...fieldProps}
{...fieldOverrideProps}
/>
);
}
return (
<React.Fragment>
<Text label>{label}</Text>
{elements}
<Text error small style={utils.my1}>
{(form.errors[name] && form.touched[name]) ? form.errors[name] : ' '}
</Text>
</React.Fragment>
);
}}
</Field>
);
export default FieldGroup;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment