Answer a question

How do I access value of the SelectField named countryCode in my React component? Use case is that validation scheme should change according to the countryCode.

  <Formik
    onSubmit={(values, actions) => this.onSubmit(values, actions.setFieldError)}
    validationSchema={() => this.registrationValidationSchema()}
    enableReinitialize={true}
    initialValues={this.props.initialData}
  >
      <Form>
          <Field
            name="countryCode"                                
            component={SelectField}
            label="Country"
            labelClassName="required"
            options={Object.entries(sortedCountryList).map(x => ({
                      value: x[1][1],
                      label: x[1][0]
                    }))}
          />
      </Form>
  </Formik>

I have tried to access it via a ref, then via this.props.values (as suggested in getFieldValue or similar in Formik) but both return just undefined or null. My props don't have any "values" field.

EDIT: Found an ugly way: document.getElementsByName("countryCode")[0].value. A better way is appreciated.

Answers

You can access values like this:

<Formik
    onSubmit={(values, actions) => this.onSubmit(values, 
    actions.setFieldError)}
    validationSchema={() => this.registrationValidationSchema()}
    enableReinitialize={true}
    initialValues={this.props.initialData}
        >
          {({
            setFieldValue,
            setFieldTouched,
            values,
            errors,
            touched,
          }) => (
            <Form className="av-tooltip tooltip-label-right">
              // here you can access to values
              {this.outsideVariable = values.countryCode}
            </Form>
            )}
        </Formik>
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐