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.
import React from 'react'; import { Field } from 'formik'; const RadioButton = (props) => { const { label, name, options, ... rest } = props; return ( <div> <label htmlFor={name}>{label}</label> <Field name={name} {... rest} > { ({ field }) => { return options. map(option => { return ( <React.
Formik can be easily used/integrated with Material UI, with just passing a few formik props to the respective Material UI Component props.
To do so, go to RadioButton. js and modify the return block to the following: import {Pressable} from 'react-native'; //additional import. //code to change of 'return' block in RadioButton.
Using a Radio Button Group with a FormSet up a form with a radio button group like this. As you can see in the above example, in the form there are three different radio buttons along with the submit button, and each radio button is attached with one onChange function, called onValueChange() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With