DEV Community

Tyler Smith
Tyler Smith

Posted on • Updated on

How to implement a working checkbox component in Formik 1.5.8

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.

Discussion (4)

Collapse
alexwhin profile image
Alex Whinfield

Working great thank you, I'm using it with TypeScript so here is my component for anybody that may be interested.

import React from "react";
import { Field, FieldProps } from "formik";

interface Props {
  id: string;
  name: string;
  className: string;
}

export const Checkbox = ({ id, name, className }: Props): JSX.Element => (
  <Field
    name={name}
    render={({ field }: FieldProps) => (
      <input
        id={id}
        {...field}
        type="checkbox"
        className={className}
        checked={field.value}
      />
    )}
  />
);
Collapse
weswedding profile image
Weston Wedding

This post helped me out of a jam, thanks! I had to modify the class prop into className but otherwise it worked great!

Collapse
tylerlwsmith profile image
Tyler Smith Author

Glad it helped, and good catch! I changed it to className on my snippet.

Collapse
doublejosh profile image
-✁-- ɥsoɾǝlqnop ---

Cool, but the field can't be unchecked with this solution 😂