Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access current value of a formik field without submitting?

Tags:

reactjs

formik

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.

like image 581
schlingel Avatar asked Mar 02 '20 15:03

schlingel


3 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>
like image 140
aturan23 Avatar answered Nov 04 '22 18:11

aturan23


You can use ref, if you need the values outside formik

   const ref = useRef(null);
   
   const someFuncton = () => {
       console.log(ref.current.values)
   }
   
   <Formik
       innerRef={ref}
       onSubmit={(values, actions) => this.onSubmit(values,
       actions.setFieldError)}
       validationSchema={() => this.registrationValidationSchema()}
       enableReinitialize={true}
       initialValues={this.props.initialData}
   
   />
       <form></form>
   </Formik>
like image 24
Muhammed Rafeeq Avatar answered Nov 04 '22 16:11

Muhammed Rafeeq


you can get it from formik using the Field comp as a wrapper

import React, { ReactNode } from 'react';
import { Field, FieldProps } from 'formik';
(...other stuffs)

const CustomField = ({
  field,
  form,
  ...props
}) => {
  const currentError = form.errors[field.name];
  const currentField = field.name;  <------ THIS

  const handleChange = (value) => {
    const formattedDate = formatISODate(value);
    form.setFieldValue(field.name, formattedDate, true);
  };

  const handleError = (error: ReactNode) => {
    if (error !== currentError) {
      form.setFieldError(field.name, `${error}`);
    }
  };

  return (
      <TextField
        name={field.name}
        value={field.value}
        variant="outlined"
        helperText={currentError || 'happy helper text here'}
        error={Boolean(currentError)}
        onError={handleError}
        onChange={handleChange}
        InputLabelProps={{
          shrink: true,
        }}
        inputProps={{
          'data-testid': `${field.name}-test`, <---- very helpful for testing
        }}
        {...props}
      />
    </MuiPickersUtilsProvider>
  );
};


export default function FormikTextField({ name, ...props }) {
  return <Field variant="outlined" name={name} component={CustomField} fullWidth {...props} />;
}

like image 1
Jesse Lewis Avatar answered Nov 04 '22 16:11

Jesse Lewis