Cannot get Material UI radio buttons to work with Formik

Viewed 8120

I am trying to use Material UI radio buttons with Formik, and they are not clicking properly. I've reduced the problem to the following example: https://codesandbox.io/s/amazing-currying-s5vn0

If anyone knows what I might be doing wrong, or if there is a bug in either system, then please let me know. When clicking on the buttons in the above example, they do not stay clicked. I have a more complex react functional component that uses other library components, so I cannot include it here. It is behaving a little differently: the buttons stay clicked even after clicking a different button. It may or may not be the same issue. Thanks in advance.

2 Answers

You need to be rendering the radio buttons inside of the FormikRadioGroup component you are rendering as a Formik Field. That way you can actually pass the props being managed by Formik down to the components to be used, as well as allow the RadioGroup component to make sure only one button is clicked at a time. I added an options prop to provide a way to pass an array of radio options and removed all of the elements you were rendering outside of that component:

const FormikRadioGroup = ({
  field,
  form: { touched, errors },
  name,
  options,
  ...props
}) => {

  return (
    <React.Fragment>
      <RadioGroup {...field} {...props} name={name}>
        {options.map(option => (
          <FormControlLabel value={option} control={<Radio />} label={option} />
        ))}
      </RadioGroup>

      {touched[fieldName] && errors[fieldName] && (
        <React.Fragment>{errors[fieldName]}</React.Fragment>
      )}
    </React.Fragment>
  );
};

Fork here.

EDIT: Updated the sandbox with an alternate example using a render function as a child within the Field component.

import { FormControlLabel, Radio, LinearProgress } from '@material-ui/core';
import { Formik, Field } from 'formik';
import { RadioGroup } from 'formik-material-ui';

<Formik {...otherProps}>
  {({ isSubmitting }) => (
    <Field component={RadioGroup} name="activity">
      <FormControlLabel
        value="painting"
        control={<Radio disabled={isSubmitting} />}
        label="Painting"
        disabled={isSubmitting}
      />
      <FormControlLabel
        value="drawing"
        control={<Radio disabled={isSubmitting} />}
        label="Drawing"
        disabled={isSubmitting}
      />
      <FormControlLabel
        value="none"
        control={<Radio disabled={isSubmitting} />}
        label="None"
        disabled
      />
    </Field>
  )}
</Formik>;

Now this is documented! Using RadioGroup from formik-material-ui.

https://stackworx.github.io/formik-material-ui/docs/api/material-ui/

Related