Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created July 23, 2019 15:17
Show Gist options
  • Save sibelius/c5d1f0f5d62f274a389026bad37a489a to your computer and use it in GitHub Desktop.
Save sibelius/c5d1f0f5d62f274a389026bad37a489a to your computer and use it in GitHub Desktop.
useCheckboxString to handle a list of checkboxes in an array of stirngs
const checkboxHandlers = useCheckboxString('myCheckboxList');
{possibleValues.map(value => (
<Checkbox
key={value}
name={value}
label={t(value)}
{...checkboxHandlers(disability)}
/>
))}
import { useField, useFormikContext } from 'formik';
export const useCheckboxString = (fieldName: string) => {
const formik = useFormikContext();
const { setFieldValue } = formik;
const [field] = useField(fieldName);
const onChange = (checkboxValue: string) => (event: React.ChangeEvent<HTMLInputElement>, isInputChecked: boolean) => {
if (isInputChecked) {
return setFieldValue(fieldName, [...field.value, checkboxValue]);
} else {
return setFieldValue(fieldName, field.value.filter(item => item !== checkboxValue));
}
};
const isChecked = (checkboxValue: string) => {
return field.value.includes(checkboxValue);
};
const getCheckboxHandler = (checkboxValue: string) => {
return {
onChange: onChange(checkboxValue),
checked: isChecked(checkboxValue),
};
};
return getCheckboxHandler;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment