Not sure how to add a Radio group to a pre-existing Formik form that also uses material UI

73 views Asked by At

I'm new to REACT and I'm trying to learn by modifying existing examples: Here I am following a tutorial that is using both Formik & Material UI, I am struggling to change a text input box to a radio group selection

<TextField
                  label="Skill Level"
                  onBlur={handleBlur}
                  onChange={handleChange}
                  value={values.skillLevel}
                  name="skillLevel"
                  error={
                    Boolean(touched.skillLevel) && Boolean(errors.skillLevel)
                  }
                  helperText={touched.skillLevel&& errors.skillLevel}
                  sx={{ gridColumn: "span 4" }}
                />

How can I change the code to add a radio button? I simply want to select between Male & Female or different pre-defined skill levels (beginner, intermediate, advanced).

<div id="my-radio-group">Picked</div>
          <div role="group" aria-labelledby="my-radio-group">
            <label>
              <Field type="radio" name="picked" value="One" />
              One
            </label>
            <label>
              <Field type="radio" name="picked" value="Two" />
              Two
            </label>
            <div>Picked: {values.picked}</div>
          </div>

This is the example on the Formik website, but I want to combine it in to that material UI wrapper

Can anyone help please? Much appreciated!

I've searched online and tried using ChatGPT to get some examples but none quite for what I am trying to do. It's a little daunting to find a similar example.

1

There are 1 answers

0
CHues On

I think you're after the component prop in the formik field component (formik component prop docs). This is where you can use a custom component.

For it to work with Formik you will need to use the field and form props that are passed down from the formik Field component. You can use these to get and update the values of the form field.

this example is taken from the formik docs that I've linked to:

// Renders a CustomInputComponent

<Field name="firstName" component={CustomInputComponent} placeholder="First Name"/>

const CustomInputComponent = ({
   field, // { name, value, onChange, onBlur }
   form: { touched, errors }, 
   // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
   ...props
 }) => (
   <div>
     <input type="text" {...field} {...props} />
     {touched[field.name] &&
       errors[field.name] && <div className="error">{errors[field.name]}</div>}
   </div>
 );

If you don't want to write custom components, there is the formik-mui package that might save you some time.

(Edit): Here is a link to the formik-mui RadioGroup documentation