How to receive select value in handlesubmit function with formik react js?

陌路散爱 提交于 2019-12-13 12:17:52

问题


i am developing a form in reactjs using formik plugin plugin link. when i submit form i am getting text fields values but dropdown values are coming empty...

this is my dropdown select

<div className="form-group">                  
                <Field component="select" id="category" name="category" value={this.state.value} className={"form-control"} onChange={ this.handleChange }>
                   <option value="lokaler">Lokaler</option>
                   <option value="jobb">Jobb</option>
                   <option value="saker-ting">Saker & ting</option>
                   <option value="evenemang">Evenemang</option>
                </Field>
                  </div>

handle submit function

export default withFormik({
  enableReinitialize: true,
  mapPropsToValues({ category }) {
    return {      
      category: category || ''
    }
  },
    handleSubmit(values, { setStatus, setErrors }){
      console.log("data is this: "); 
      console.log(values); //here i am getting all form fields values except select value returning empty value
      console.log("category: "+values.category);// here i always get empty value but not getting selected value

      }

i am getting all text fields values in handle submit function but i am not able to get dropdown selected value....kindly tell me how to get dropdown select value in handle submit function ?


回答1:


I also faced this problem yesterday. My problem was to submit form that contains ant design dropdown. I finally make it work after hours of:

  • revisiting the Formik Docs
  • watch Andrew Mead's video Better React Form with Formik again.
  • also viewing Jared Palmer's Working with 3rd-party inputs #1: react-select

The doc said you need to set onChange, onBlur events to setFieldValue, setFieldTouched props respectively like 3rd-party input example:

<MySelect
    value={values.topics}
    onChange={setFieldValue}
    onBlur={setFieldTouched}
    error={errors.topics}
    touched={touched.topics}
/>

So to my problem, I need to change a bit:

<Select
  {...field}
  onChange={(value) => setFieldValue('fruitName', value)}
  onBlur={()=> setFieldTouched('fruitName', true)}
  value={values.fruitName}
  ...
>
...
</Select>

Hope this will help.

Here is my CodeSandbox




回答2:


A more robust way to handle select components whilst using Formik would be to also use Jed Watsons react-select component. The two work together nicely and abstract away a lot of the boilerplate you would normally need to implement to get the component working seamlessly with Formik.

I have forked a simple example from Jared Palmer's react-select / Formik example on codesandbox and adjusted it to reflect your code above.

import "./formik-demo.css";
import React from "react";
import { render } from "react-dom";
import { withFormik } from "formik";
import Select from "react-select";
import "react-select/dist/react-select.css";

const options = [
  { value: "lokaler", label: "Lokaler" },
  { value: "jobb", label: "Jobb" },
  { value: "saker-ting", label: "Saker & ting" },
  { value: "evenemang", label: "Evenemang" }
];

const MyForm = props => {
  const {
    values,
    handleChange,
    handleBlur,
    handleSubmit,
    setFieldValue
  } = props;
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="myText" style={{ display: "block" }}>
        My Text Field
      </label>
      <input
        id="myText"
        placeholder="Enter some text"
        value={values.myText}
        onChange={handleChange}
        onBlur={handleBlur}
      />
      <MySelect value={values.option} onChange={setFieldValue} />
      <button type="submit">Submit</button>
    </form>
  );
};

class MySelect extends React.Component {
  handleChange = value => {
    // this is going to call setFieldValue and manually update values.topcis
    this.props.onChange("option", value);
  };
  render() {
    return (
      <div style={{ margin: "1rem 0" }}>
        <label htmlFor="color">Select an Option </label>
        <Select
          id="color"
          options={options}
          onChange={this.handleChange}
          value={this.props.value}
        />
      </div>
    );
  }
}

const MyEnhancedForm = withFormik({
  mapPropsToValues: props => ({
    myText: "",
    option: {}
  }),
  handleSubmit: (values, { setSubmitting }) => {
    console.log(values);
  }
})(MyForm);

const App = () => <MyEnhancedForm />;
render(<App />, document.getElementById("root"));

There are a few gotchas, you have to include the react select css for the component to display properly

import "react-select/dist/react-select.css";

the function mapPropsToValues option field should be initialised to an object

 mapPropsToValues: props => ({
    myText: "",
    option: {}

Finally here is a link to the codesandbox example



来源:https://stackoverflow.com/questions/50343914/how-to-receive-select-value-in-handlesubmit-function-with-formik-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!