Cannot get Material UI radio buttons to work with Formik
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.