DEV Community

How to implement a working checkbox component in Formik 1.5.8

Tyler Smith on October 20, 2019

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 c...
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

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 😂