Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the initial value for a radio button group in Formik

Tags:

reactjs

formik

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!

like image 857
SkyeBoniwell Avatar asked Oct 26 '25 07:10

SkyeBoniwell


1 Answers

charRace initial value has to be a string. You can test here

https://codesandbox.io/s/trusting-hofstadter-hihhj

<Formik
    initialValues={{
        charId: id,
        charName: name,
        charClass: class,
        charRace: String(race),
        charAge: age,
        charRegion: region
    }}
    
like image 114
GitGitBoom Avatar answered Oct 28 '25 21:10

GitGitBoom