I was building a form with Formik and I needed a single checkbox to mark a post as "published". In Formik 1.5.8, my values values weren't mapping correctly to checkboxes, so I created a generic Checkbox component to use instead of the Formik Field component.
import { Field } from "formik";
export default function Checkbox({ id, name, className }) {
return (
<>
<Field
name={name}
render={({ field, form }) => {
return (
<input
type="checkbox"
id={id}
className={className}
checked={field.value}
{...field}
/>
);
}}
/>
</>
);
}
I only used for a single true/false value, so your mileage may vary if you're working on something else.
I extracted the code above from this CodeSandbox, so please check it out. I think it'll show you how to do a little more than my implementation does.
It looks like the checkbox issue will be fixed in version 2 of Formik according to its author Jared Palmer, but this should be a workable solution until then.
Top comments (4)
Working great thank you, I'm using it with TypeScript so here is my component for anybody that may be interested.
This post helped me out of a jam, thanks! I had to modify the
class
prop intoclassName
but otherwise it worked great!Glad it helped, and good catch! I changed it to className on my snippet.
Cool, but the field can't be unchecked with this solution 😂