Dynamically setFieldValue to group of checkboxes in formik

Viewed 23

MY Problem I am trying the set the field values to the group of checkboxes using the formik.setFieldValue property. These values are coming from a backend API in the form of an array.

My Code I am using the useFormik hook of the formik library to handle checkbox values. I have set up the formik.handleChange on my checkboxes onChange function. Here is the bare minimum code snippet of my application.

import React from "react";
import { useFormik } from "formik";



const tags = ["one", "two", "three"];

const ProjectsForm = () => {
  const formik = useFormik({
    enableReinitialize: true,
    initialValues: {
      tags: []
    },
    onSubmit: (values) => {
      console.log(values);
    }
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      {tags.map((tag) => (
        <div key={tag}>
          <input
            id={tag}
            type="checkbox"
            name={tag}
            
            onChange={formik.handleChange}
          />
          <label htmlFor={tag}>{tag}</label>
        </div>
      ))}
      <button type="submit">Submit</button>
    </form>
  );
};


How do I use the formik.setFieldValue to set the value to my checkboxes coming from the backend?

0 Answers
Related