How to implement a working checkbox component in Formik 1.5.8

Tyler Smith - Oct 20 '19 - - Dev Community

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}
            />
          );
        }}
      />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player