Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox onChange event is not handled by handleChange props by Formik

Tags:

reactjs

formik

I was building simple Form using React and Formik library. I have added check box inside the form tag which is wrapped by withFormik wrapper of formik library.

I have tried to changing from

<input
  type="checkbox"
  name="flag"
  checked={values.flag}
  onChange={handleChange}
  onBlur={handleBlur}
/>

to

<input
  type="checkbox"
  name="flag"
  value={values.flag}
  onChange={handleChange}
  onBlur={handleBlur}
/>

but none is working.

the component is as following

import { withFormik } from 'formik';
...

const Form = props => (
  <form>
    <input
      type="checkbox"
      name="flag"
      checked={props.values.flag}
      onChange={props.handleChange}
      onBlur={props.handleBlur}
    />
    <input
      type="text"
      name="name"
      checked={props.values.name}
      onChange={props.handleChange}
      onBlur={props.handleBlur}
    />
  </form>
);

const WrappedForm = withFormik({
  displayName: 'BasicForm',
})(Form);

export default WrappedForm;

It should change props.values when clicking checkbox. but it doesn't change props data at all.

Btw, it changes props data when typing in text input box. This only happens with checkbox.

like image 882
Derek Jin Avatar asked Sep 09 '19 09:09

Derek Jin


2 Answers

Using the setFieldValue from Formik props, you can set the value of the check to true or false.

<CheckBox
checked={values.check}
onPress={() => setFieldValue('check', !values.check)}
/>

My answer relates to react-native checkbox.

This article is very helpful. https://heartbeat.fritz.ai/handling-different-field-types-in-react-native-forms-with-formik-and-yup-fa9ea89d867e

like image 102
Tamunoibi Aprekuma Avatar answered Dec 06 '22 00:12

Tamunoibi Aprekuma


Im using react material ui library, here is how i manage my checkboxes :

import { FormControlLabel, Checkbox} from "@material-ui/core";
import { Formik, Form, Field } from "formik";

         <Formik
            initialValues={{
              check: false
            }}
           onSubmit={(values, { setSubmitting }) => {
            setTimeout(() => {
              alert(JSON.stringify(values, null, 2));
              setSubmitting(false);
            }, 400);
          }}
        >
          {({ values, setFieldValue }) => (
            <Form className="gt-form">
              <FormControlLabel
                checked={values.check}
                onChange={() => setFieldValue("check", !values.check)}
                control={<Checkbox />}
                label="save this for later"
              />
            </Form>
          )}
        </Formik>
like image 23
Abdelghafour Ennahid Avatar answered Dec 05 '22 23:12

Abdelghafour Ennahid