Setting the initial value for a radio button group in Formik

Viewed 5010

I am using the latest version of the react form library called Formik (2.1.5).

It's pretty nice, but I'm having issues with a radio button group on the initial load.

When I first load the form, I have a bunch of initial values set.

I can see them when I do a console.log and all the data is there.

My input fields and text fields load the initial values just perfectly.

But my radio button group doesn't show which radio button should be selected.

Here is my code for the radio button group:

<label htmlFor="radioGroup" style={{ display: "block" }}>
    Character Race
</label>
<label>
    <Field type="radio" name="charRace" value="1" />
    Human
</label>
<label>
    <Field type="radio" name="charRace" value="2" />
    Elf
</label>
<label>
    <Field type="radio" name="charRace" value="3" />
    Dwarf
</label>

And when the form loads, here is the initial values:

<Formik
    initialValues={{
        charId: id,
        charName: name,
        charClass: class,
        charRace: race
        charAge: age,
        charRegion: region
    }}
    

Now when the form loads, and the fields for charId, charName, charClass, charAge, and charRegion are all filled out properly.

And when I do a console.log for the values, I see them all...for example:

charId: 3728,
charName:  Jeriod,
charClass: Wizard,
charRace: 1,
charAge:  34,
charRegion: North

But I can't figure out how to get the charRace radio button group to have the correct radio button checked. They are all always unchecked.

Any help would be loved , thanks!

2 Answers

Not sure if this is the right strategy to adopt..

I added a 'checked' attribute to the radio button I wanted to pre-select. Mentioning in initialValues within Formik alone didn't work for me.

Related