Search code examples
javascriptreactjssemantic-uiformiksemantic-ui-react

How to define setFieldValue in React


I'm using Formik for validating the fields before creating an entity. There is a Select which opens a dropdown and the user must choose one option from there.

I get an error saying that setFieldValue is not defined but where I've researched before I didn't find any definition of this method, it is just used like that so I don't know why is this happening.

This is my code:

import React from 'react';
import { Formik, Form, Field } from 'formik';
import { Button, Label, Grid } from 'semantic-ui-react';
import * as Yup from 'yup';

class CreateCompanyForm extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      industry: '',
    };
  }

  onChange = (e, { name, value }) => {
    this.setState({ [name]: value });
  };

  handleSubmit = values => {
    // ...
  };

  render() {
    const nameOptions = [
      { text: 'Services', value: 'Services' },
      { text: 'Retail', value: 'Retail' },
    ];

    const initialValues = {
      industry: '',
    };
    const requiredErrorMessage = 'This field is required';
    const validationSchema = Yup.object({
      industry: Yup.string().required(requiredErrorMessage),
    });
    return (
      <div>
        <div>
          <Button type="submit" form="amazing">
            Create company
          </Button>
        </div>

        <Formik
          htmlFor="amazing"
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={values => this.handleSubmit(values)}>
          {({ errors, touched }) => (
            <Form id="amazing">
              <Grid>
                <Grid.Column>
                  <Label>Industry</Label>
                  <Field
                    name="industry"
                    as={Select}
                    options={nameOptions}
                    placeholder="select an industry"
                    onChange={e => setFieldValue('industry', e.target.value)}  // here it is
                  />

                  <div>
                    {touched.industry && errors.industry
                      ? errors.industry
                      : null}
                  </div>
                </Grid.Column>
              </Grid>
            </Form>
          )}
        </Formik>
      </div>
    );
  }
}

The error says: 'setFieldValue' is not defined no-undef - it is from ESLint. How can be this solved?


Solution

  • setFieldValue is accessible as one of the props in Formik.

    I tried it on CodeSandbox, apparently, the first parameter in the onChange prop returns the event handler while the second one returns the value selected onChange={(e, selected) => setFieldValue("industry", selected.value) }

        <Formik
          htmlFor="amazing"
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={(values) => this.handleSubmit(values)}
        >
          {({ errors, touched, setFieldValue }) => (
            //define setFieldValue
            <Form id="amazing">
              <Grid>
                <Grid.Column>
                  <Label>Industry</Label>
                  <Field
                    id="industry" // remove onBlur warning
                    name="industry"
                    as={Select}
                    options={nameOptions}
                    placeholder="select an industry"
                    onChange={(e, selected) =>
                      setFieldValue("industry", selected.value)
                    }
                  />
    
                  <div>
                    {touched.industry && errors.industry
                      ? errors.industry
                      : null}
                  </div>
                </Grid.Column>
              </Grid>
            </Form>
          )}
        </Formik>