lundi 12 juillet 2021

Formik checkbox value not showing checked for a true value

I'm using Formik with Material-UI/Stepper and I am having issues showing a checkbox that has a formik state value of true being checked.

Within my form, I am using the Material-UI stepper. The issue I am facing is that on page 1 of my form, I am using a checkbox (FormControlLabel API). When I click on the checkbox, the formik state value for this is true but when I advance to the next page and then press the back button to return to page 1 where my checkbox is, the formik state value still maintains the true value but my checkbox is no longer checked.

Below is the code that I am using to render my checkbox but I'm not sure why the checkbox is not showing as checked for a true value?

I added the code checked={field.checked} within the FormControlLabel api but made no difference.

import React from 'react';
import {
  Checkbox,
  FormControl,
  FormControlLabel,
  FormGroup,
  FormLabel
} from '@material-ui/core';
import { useField, useFormikContext } from 'formik';

const CheckboxWrapper = ({
  name,
  label,
  legend,
  ...otherProps
}) => {
  const { setFieldValue } = useFormikContext();
  const [field, meta] = useField(name);

  const handleChange = evt => {
    const { checked } = evt.target;
    setFieldValue(name, checked);
  };

  const configCheckbox = {
    ...field,
    onChange: handleChange
  };

  const configFormControl = {};
  if (meta && meta.touched && meta.error) {
    configFormControl.error = true;
  }

  return (
    <FormControl {...configFormControl}>
      <FormLabel component="legend">{legend}</FormLabel>
      <FormGroup>
        <FormControlLabel
          control={<Checkbox {...configCheckbox} />}
          label={label}
          checked={field.checked}
        />
      </FormGroup>
    </FormControl>
  );
};

export default CheckboxWrapper;

The way I am calling the above within my actual form is as follows:

      <Checkbox 
        name="termsAgreement"
        label="I agree"
      />

where name="termsAgreement" is my formik initial state value.

Any help would be great.




Aucun commentaire:

Enregistrer un commentaire