最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to define setFieldValue in React - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Sep 7, 2020 at 9:09 Leo MessiLeo Messi 6,17622 gold badges77 silver badges153 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

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>

try calling it using this structure onChange = {v => formik.setFieldValue('field', v)}

<Formik
  htmlFor="amazing"
  initialValues={initialValues}
  value={{industry:this.state.industry}}
  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) =>
              this.setState({
                industry: e.target.value,
              })
            } // here it is
          />

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

Replace your onChange by onChange={this.onChange('industry', e.target.value)} and in your constructor add this line this.onChange = this.onChange.bind(this). your onChange methode will be:

onChange(e, { name, value }){
   this.setState({ [name]: value });
 }
发布评论

评论列表(0)

  1. 暂无评论