0
votes

I am trying to wrap formik around material ui react form components. It works well with TextField component. Please find the code below:

<TextField
              id="firstName"
              name="firstName"
              label="First Name"
              variant="outlined"
              autoComplete="off"
              value={formik.values.firstName}
              onChange={formik.handleChange}
              error={
                formik.touched.firstName && Boolean(formik.errors.firstName)
              }
              helperText={formik.touched.firstName && formik.errors.firstName}
              className={classes.controls}
            />

But how do I wrap it around radio buttons:

<FormControl component="fieldset" className={classes.controls}>
              <FormLabel component="legend">Gender</FormLabel>
              <RadioGroup aria-label="gender" name="gender">
                <FormControlLabel
                  value="male"
                  control={<Radio />}
                  label="Male"
                />
                <FormControlLabel
                  value="female"
                  control={<Radio />}
                  label="Female"
                />
              </RadioGroup>
            </FormControl>

Could not find enough documentation to fix that bit. Could anyone please help.

thanks

1
Can you provide a codesandbox or sth of your code? Meanwhile this might help: your control component might receive onChange attribute. <FormControlLabel control={<Checkbox checked={apple} onChange={handleChange} name="apple" />} label="Apple" />c0m1t

1 Answers

0
votes

I did the following to implement radio group buttons:

import { FormControlLabel, Radio } from "@material-ui/core";
import * as yup from "yup";

export function RadioButtonGroup(props) {
  const [field] = useField({
    name: props.name,
    type: "radio",
    value: props.value,
  });
  return (
    <FormControlLabel
      control={<Radio {...props} {...field} />}
      label={props.label}
    />
  );
}

Add the following code inside the form:

      <RadioButtonGroup name="gender" value="male" label="Male" />
      <RadioButtonGroup name="gender" value="female" label="Female" />

For validation:

const validationSchema = yup.object({
  gender: yup.string().required("Gender is required"),
});