Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Formik Default value

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>
like image 885
Nabin Singh Avatar asked Jun 15 '20 20:06

Nabin Singh


People also ask

How do I use formik with react context?

Method 2: Using Formik with React context The <Formik/> component exposes various other components that adds more abstraction and sensible defaults. For example, components like <Form/ >, <Field/>, and <ErrorMessage/> are ready to go right out of the box.

How to set default value in select using ReactJS?

- GeeksforGeeks How to set default value in select using ReactJS ? In HTML, the ‘ selected’ attribute in the option tag is used to set the default value in the select menu. The same approach can also be used with React to set a default value if we are not using React Select Component.

How to change the default value of a formik component?

Below is my code: 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: the {...field} spread operator of field already has the "value" added

What is the use of initial values in formik?

Initial field values of the form, Formik will make these values available to render methods component as values. Even if your form is empty by default, you must initialize all fields with initial values otherwise React will throw an error saying that you have changed an input from uncontrolled to controlled.


4 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:

  • https://jaredpalmer.com/formik/docs/api/field
like image 121
jmunsch Avatar answered Oct 11 '22 10:10

jmunsch


you can set enableReinitialize option to true

your formik hook


const formik = useFormik({
        enableReinitialize: true,
        initialValues: $yourState
})
like image 22
hamidreza nikoonia Avatar answered Oct 11 '22 11:10

hamidreza nikoonia


<Formik

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

working here

like image 20
GM Taium Ahmed Avatar answered Oct 11 '22 10:10

GM Taium Ahmed


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.

like image 41
Anthony Avila Avatar answered Oct 11 '22 10:10

Anthony Avila