Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Checkbox doesn't bind to initialValues #1050

Closed
dem0nbruce opened this issue Oct 26, 2018 · 25 comments
Closed

Checkbox doesn't bind to initialValues #1050

dem0nbruce opened this issue Oct 26, 2018 · 25 comments

Comments

@dem0nbruce
Copy link

🐛 Bug report

Current Behavior

When using <Field type="checkbox /> and initialValues the checkbox doesn't bind.

Expected behavior

<Field type="checkbox" /> should bind to initialValues

Reproducible example

https://codesandbox.io/s/ppy7wyrl0m

Suggested solution(s)

See #1024

Additional context

See #1024

Your environment

Software Version(s)
Formik 1.3.1
React 16.5.2
@pahen
Copy link

pahen commented Oct 30, 2018

This worked as a workaround for me.

const CheckboxInput = (props) => (
	<Field {...props} render={({field}) => <input {...field} type="checkbox" checked={field.value} />} />
);

@amcvitty
Copy link

This workaround is a little simpler, adding the checked property on the Field (works since the props get spread onto the input)

<Field type="checkbox" name="box" checked={props.values.box} />

@stale
Copy link

stale bot commented Dec 30, 2018

Hola! So here's the deal, between open source and my day job and life and what not, I have a lot to manage, so I use a GitHub bot to automate a few things here and there. This particular GitHub bot is going to mark this as stale because it has not had recent activity for a while. It will be closed if no further activity occurs in a few days. Do not take this personally--seriously--this is a completely automated action. If this is a mistake, just make a comment, DM me, send a carrier pidgeon, or a smoke signal.

@stale stale bot added the stale label Dec 30, 2018
@stale
Copy link

stale bot commented Jan 6, 2019

ProBot automatically closed this due to inactivity. Holler if this is a mistake, and we'll re-open it.

@stale stale bot closed this as completed Jan 6, 2019
@RazerM
Copy link

RazerM commented Jan 28, 2019

I think this is still a problem.

In the following sandbox, the initialValues only works when <Field /> isn't given type="checkbox".

https://codesandbox.io/s/p7zlvk86lm

@seunggs
Copy link

seunggs commented Mar 15, 2019

I also think this is still a problem - can't seem to set checkbox initial values using initialValues

@madroneropaulo
Copy link

Seems that this is being fixed here #1115

@tonyhallett
Copy link

This is still an issue

@eenewbsauce
Copy link

This is pretty sad guys...

@jaredpalmer
Copy link
Owner

@jaredpalmer
Copy link
Owner

jaredpalmer commented Jul 11, 2019

Updated the initial codesandbox to Formik 2 and React 16.8.6 (something with hooks)

https://codesandbox.io/s/formik-v2-field-checkbox-binding-vdvty

@prajavk
Copy link

prajavk commented Jul 24, 2019

Please suggest work around for checkbox with Field render for formik 1.5.7

@KrallXZ
Copy link

KrallXZ commented Aug 3, 2019

Please suggest work around for checkbox with Field render for formik 1.5.7

@prajavk , It works for me:

<Field type="checkbox" name="manual-only" id="manual-only" onChange={event => setFieldValue('manualOnly', event.target.checked)} checked={values.manualOnly} />

@kkarkos
Copy link

kkarkos commented Aug 6, 2019

Workaround with react-native

<CheckBox color="#000"
                      onPress={event =>
                        props.setFieldValue("terms", !props.values.terms)
                      }
                      checked={props.values.terms}
                    />

@ChibiOokami86
Copy link

Still experience this in formik 1.5.8
Hoping more comments results in this getting patched.

Followed @RazerM 's comment and removed type="checkbox" as a workaround.

@ghost
Copy link

ghost commented Nov 19, 2019

I have the same problem. Third formik bug I have run into since starting to use the library last week... faith has been shaken.

@alitsvin
Copy link

Not fixed yet

@entozoon
Copy link

Yep, lost an hour or so before realising this is a straight up bug.
Please re-open the issue.

The checked={value} type workaround is usable but it's unexpected that initialValues doesn't work

@chihpingkuo
Copy link

not fixed yet, however the issue has been closed

@johnrom
Copy link
Collaborator

johnrom commented Feb 5, 2021

have you checked https://codesandbox.io/s/formik-v2-field-checkbox-binding-vdvty ??

The issue here has long been fixed so far as I can tell, you may be having a similar but unrelated issue, so feel free to open a new issue with a codesandbox reproduction.

Even if the issue is it's broken in a "future" version, that's not the same as this issue which was for v1.

@AbdulBasitKhaleeq
Copy link

This is how i am using it with material UI and its working fine. the initial value is present in field.value so i assigned it checked property of checkbox.

import React from 'react';
import { at } from 'lodash';
import { useField } from 'formik';
import {
    Checkbox,
    FormControl,
    FormControlLabel,
    FormHelperText
} from '@material-ui/core';

export default function CheckboxField(props: any) {
    const { label, ...rest } = props;
    const [field, meta, helper] = useField(props);
    const { setValue } = helper;

    function _renderHelperText() {
        const [touched, error] = at(meta, 'touched', 'error');
        if (touched && error) {
            return <FormHelperText>{error}</FormHelperText>;
        }
    }

    function _onChange(e: any) {
        setValue(e.target.checked);
    }

    return (
        <FormControl {...rest}>
            <FormControlLabel
                value={field.value}
                checked={field.value}
                control={<Checkbox checked={field.value} {...field} onChange={_onChange} />}
                label={label}
            />
            {field.checked}
            {_renderHelperText()}
        </FormControl>
    );
}

@bursteways
Copy link

bursteways commented Apr 16, 2021

This worked well for me:

import { Grid, RadioGroup } from '@material-ui/core';
import { FormikBooleanRadioField } from '......./';

return (
  ...
 <fieldset>
    <legend>Do you like pizza?</legend>
    <RadioGroup aria-label="Do you like pizza?">
      <Grid container spacing={2}>
        <Grid item>
          <FormikBooleanRadioField name="Yes" formikKey="likesPizza" value />
        </Grid>
        <Grid item>
          <FormikBooleanRadioField name="No" formikKey="likesPizza" value={false} />
        </Grid>
      </Grid>
    </RadioGroup>
</fieldset>
)
import { changeEvent, ReactElement } from 'react';
import { useField, useFormikContext } from 'formik';
import get from 'lodash/get';

// Types
interface IProps {
  formikKey: string;
  name: string;
  value: boolean;
}

export const FormikBooleanRadioField = ({ formikKey, value, ...rest }: IProps): ReactElement => {
  const [field] = useField(rest);
  const { setFieldValue, values } = useFormikContext();
  const onChange = (e: ChangeEvent<HTMLInputElement>): void => {
    setFieldValue(formikKey, e.target.value === 'Yes');
  };
  const formikValue: boolean = get(values, formikKey);

  return (
    <label key={formikKey} className="form-input-radio">
      <input
        {...field}
        checked={value === formikValue}
        id={`${formikKey}.${field.name}`}
        name={formikKey}
        onChange={onChange}
        type="radio"
        value={field.name}
      />
      <span className="checkmark">
        <div className="label-text-container">
          <div className="label-text">{field.name}</div>
        </div>
      </span>
    </label>
  );
};

FormikModel:

{ likesPizza: true }

@tavioo
Copy link

tavioo commented Jun 28, 2021

I was having this issue with a checkbox group, so I'm leaving this here in case someone else has the same problem and google brings them here. This also uses material ui:

export type CheckboxGroupOptions = { value: string; label: string }[];

export interface Props {
  field: FieldInputProps<string>;
  options: CheckboxGroupOptions;
}

const CheckboxGroup = ({ field, options }: Props) => {
  return (
    <FormGroup>
      {options.map((option, i) => (
        <FormControlLabel
          key={i}
          control={
            <Checkbox
              name={field.name}
              value={option.value}
              onChange={field.onChange}
              checked={field.value.includes(option.value)}
            />
          }
          label={option.label}
        />
      ))}
    </FormGroup>
  );
};
export default CheckboxGroup

@idesignpixels
Copy link

Still an issue, initial values not being honoured for checkbox.

@darrena092
Copy link

Still an issue on 2.2.9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.