Skip to content

Instantly share code, notes, and snippets.

@gyfchong
Created February 9, 2021 08:25
Show Gist options
  • Save gyfchong/d8473ce0f6c744e9c91a0b60bc972756 to your computer and use it in GitHub Desktop.
Save gyfchong/d8473ce0f6c744e9c91a0b60bc972756 to your computer and use it in GitHub Desktop.
const Checkbox = props => {
const CHECKBOX_NAME = props.name;
const CHECKBOX_VALUE = props.value;
// Using Formik Hooks, pass the checkbox name as the field we would like to use
const [field, meta, helper] = useField(CHECKBOX_NAME);
// Get the current checked state of the field based on its value
const isChecked = !!field.value[CHECKBOX_VALUE];
const handleChange = () => {
// And set the value of the field to an object
// containing the checked state's opposite value.
helper.setValue({
...field.value,
[CHECKBOX_VALUE]: !isChecked
});
};
return (
<input
type="checkbox"
onChange={handleChange}
checked={isChecked}
{...props}
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment