Created
February 9, 2021 08:25
-
-
Save gyfchong/d8473ce0f6c744e9c91a0b60bc972756 to your computer and use it in GitHub Desktop.
This file contains 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 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