React Formik Default value

Viewed 28916

I am using React formik. I have a dropdown select option. Option is working fine but i want to have default value as Free from the dropdown. If i submit the form without click, it is giving me the option value as blank. Below is my code:

const defautValue="Free";
const options=["Premium","Gold","Free"]


<Field> 
  {(props: any)=>{
    const {field}=props;
    const defaultOption=<option key='default' value={defaultValue}>{defaultValue}</option>
    const option=options.map((i:string)=>{return (<option key={i} value={i}>{i}</option>)})
    const selectOptions=[defaultOption,...option]
    return (
       <div>
       <select value={field.value}{...field}>{selectOptions}</select>
       </div>
         )
  }}
</Field>
6 Answers

try removing the manual setting of the defaultOption, selectOptions, and use either the formik.values, or form.value, and set the defaultValue of a component using the initialValues of the Formik component:


<Formik
  initialValues={{selectedOption: "Free"}: YourFormData}
  onSubmit={(values, actions) => {console.log(values, actions)}}
>
  {formik => (
    <Form translate="yes">
      <Field name="selectedOption">
          {({ form, field }: FieldProps<YourFormData>) => {
          const options=["Premium","Gold","Free"].map((i:string)=>{return (<option key={i} value={i}>{i}</option>)})    
          return (
             <div>
                 <select {...field}>{options}</select>
             </div>
               )
        }}
      </Field>
    </Form>
    )}
</Formik>

the {...field} spread operator of field already has the "value" added

<Field name="selectedOption"> automagically connects the selectedOption formik field up to the <select> element, including onChange, onBlur, touched, etc.

Or you can also use as for example:

<Formik
    initialValues={{selectedOption: 'Free'}}
    onSubmit={(values, actions) => {
        setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
        }, 1000);
    }}>{(props: FormikProps<any>) => (
    <Form>
        <Field as="select" name="selectedOption">
           {["Premium","Gold","Free"].map((i:string)=>(<option key={i} value={i}>{i}</option>))}
        </Field>
    </Form>
)}
</Formik>

docs:

you can set enableReinitialize option to true

your formik hook


const formik = useFormik({
        enableReinitialize: true,
        initialValues: $yourState
})

<Formik

    enableReinitialize // missing piece!!
    initialValues={props.initialValues}

working here

You can add an option that is 'disabled' above the options that you are populating dynamically:

<Formik>
 <option disabled value="">(Make a Selection)</option>
 {(props: any)=>{
 //...

</Formik>

It will display as the first default option with a message of your choice, and the user won't be able to select it from the dropdown.

You are setting your key to 'default' but your value and innerHTML to {defaultValue} which I don't see defined anywhere. This could cause the blank if defaultValue is undefined.

Also you overwrote defaultOption in your inner scope because it is already defined in the outer scope

None of the above worked for me.

Here is what worked.

Formik API setFieldValue

So if you have a custom component that is getting initial values but your changing that say from a backend call, you'd use setFieldValue to get the field value updated from the initial one.

In my case, the drop down would have the initial value. It would not update unless I clicked it. I wanted the initialValue to change and this is how I did it.

<Field className='col form-control form-control-sm' id='department' name='department'>
                                {
                                    (props) => {
                                        const { field, form, meta } = props
                                        return (
                                            <DepartmentList field={field} form={form} hotelId={form.values.hotelId} />
                                        )
                                    }
                                }
                            </Field>

Inside that component, where relevant, change the FieldValue of department like this:

this.props.form.setFieldValue('department', this.state.department[0].id)
Related