schlingel
schlingel

Reputation: 1694

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

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.

Upvotes: 27

Views: 71858

Answers (5)

Yuberley Guerrero
Yuberley Guerrero

Reputation: 31

If what you want is to take the values of each input of the form you can use Formik with the hook useFormik, it is more comfortable since you can separate the form as such:

import React, { useEffect } from 'react';
import { useFormik  } from 'formik';

export const Form = () => {

    const formik = useFormik({
        initialValues: {
            name: '',
            email: '',
        },
        onSubmit: values => {
            console.log(values);
        },
    });

    useEffect(() => {
        console.log('values useEffect: ', formik.values);
    }, [formik.values.name]);

    return (
        <Box>
            <Text>Form</Text>
            <Input
                placeholder="Name"
                value={formik.values.name}
                onBlur={formik.handleBlur('name')}
                onChangeText={formik.handleChange('name')}
            />
            <Input
                placeholder="Email"
                value={formik.values.email}
                onBlur={formik.handleBlur('email')}
                onChangeText={formik.handleChange('email')}
            />
        </Box>
        
    );

};

Upvotes: 3

Satyam Choudhary
Satyam Choudhary

Reputation: 51

it is very simple just do console.log(formik.values) and you will get all the values without submitting it.

Upvotes: -2

Jesse Lewis
Jesse Lewis

Reputation: 11

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} />;
}

Upvotes: 1

Muhammed Rafeeq
Muhammed Rafeeq

Reputation: 400

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>

Upvotes: 40

aturan23
aturan23

Reputation: 5400

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>

Upvotes: 41

Related Questions