Created
July 23, 2019 15:17
-
-
Save sibelius/c5d1f0f5d62f274a389026bad37a489a to your computer and use it in GitHub Desktop.
useCheckboxString to handle a list of checkboxes in an array of stirngs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const checkboxHandlers = useCheckboxString('myCheckboxList'); | |
{possibleValues.map(value => ( | |
<Checkbox | |
key={value} | |
name={value} | |
label={t(value)} | |
{...checkboxHandlers(disability)} | |
/> | |
))} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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