Search code examples
reactjsdropdownsemantic-uiformikyup

Why can't I read Dropdown values by Formik in React?


I am using Formik and Yup for a form control in react application. I use also Semantic UI. In the application, when I click the submit button, whereas I can read the values from FormField elements and see them on Console, I can not get the values from Dropdown elements and they appear blank on Console. How can I solve this out?

 return (
    <div>
      <Card fluid>
        <Card.Content>
          <Card.Header>Create A New Job Ad</Card.Header>
          <Divider inverted />
          <Formik
            initialValues={initialValues}
            validationSchema={jobAdCreateSchema}
            onSubmit={(values) => {
              console.log(values);
            }}
          >
            <Form className="ui form">
              <label>Job Title</label>
              <FormField>
                <Field name="jobTitle" placeholder="Select a Job Title"></Field>
              </FormField>
              <FormField>
                <label>City</label>
                <Dropdown
                  name="city"
                  placeholder="Select a City"
                  fluid
                  selection
                  options={cityOption}
                />
              </FormField>
              <FormField>
                <Button color="green" type="submit">
                  Submit
                </Button>
              </FormField>
            </Form>
          </Formik>
        </Card.Content>
      </Card>
    </div>
  );

Solution

  • The issue is with the way the Dropdown component is rendered currently. You need to make use of the setFieldValue provided by Formik to manually update the Formik state.

     <Formik
        initialValues={{
          city: ""
        }}
        onSubmit={(values) => console.log(values)}
      >
        {({ values, setFieldValue }) => (
          <div>
            <pre>{JSON.stringify(values, undefined, 2)}</pre>
    
            <Dropdown
              selection
              placeholder="Select a City"
              options={[
                { value: "NY", text: "New York" },
                { value: "LA", text: "Los Angeles" },
                { value: "SF", text: "San Fransico" }
              ]}
              value={values.city}
              onChange={(value) => setFieldValue("city", value)}
            />
          </div>
        )}
      </Formik>
    

    Working Sandbox