简体   繁体   中英

How to access values from React Select and pass them to Formik values on Submit?

I want to access my React-Select elements value and pass it as values in the OnSubmit Function and added to the values collected from formik.

I have a multi-element form created in Formik. I access this form inside a Modal. In the form, I access the values of the form elements username, email, password just fine. Code Below :

  handleSubmit = (values,) => {
    const { onSuccess } = this.props;
    console.log(values);
    onSuccess(values);
  };

I also have a React-Select component, that I load some data, with a label and a value pair.

I want to add the selected value to the list of values from fomrik. The response below, gives me just this info.

  selectOnChangeCallback = response => {
    // eslint-disable-next-line no-console
    console.log('selectOnChangeCallback', response);
  };

And my React select Component:

                  <ReactSelect
                    isMulti={false}
                    options={selectData}
                    onChangeCallback={this.selectOnChangeCallback}
                  />

I access it inside the Modal, with this function:

  closeCreateUserModal = response => {
    this.setState({ isCreateUserModalOpen: false });
    // eslint-disable-next-line
    this.props.notify({
      message: `User ${response.username} was added to group `,
      status: STATUS.success,
    });

    console.log(response)

    return this.sampleGet();
  };

My form component:

const UserValidationSchema = Yup.object().shape({
  username: Yup.string('Provide a Username').required('Username is Required'),
  email: Yup.string().email('Provide a Valid email Address'),
  password: Yup.string('Provide a Password').required('Password s required'),
  confirmPassword: Yup.string('Provide your password again')
    .required('Password Confirmation is Required')
    .oneOf([Yup.ref('password')], 'Passwords do not match')
});

const INITAIL_VALUES = {
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  group: {}
};

class ViewUser extends Component {
  static propTypes = {
    ...formPropTypes,
    username: PropTypes.string,
    email: PropTypes.string,
    password: PropTypes.string,
    confirmPassword: PropTypes.string,
    groupSelect: PropTypes.func,
    onSuccess: PropTypes.func
  };

  static defaultProps = {
    email: ''
  };

  state = {
    type: 'password',
    groups: []
  };

  componentDidMount() {
    this.fetchListGroups();
  }

  fetchListGroups = () => {
    listGroups().then(({ data }) => {
      this.setState({ groups: data });
    });
  };

  mapListGroupToSelect = () => {
    const { groups } = this.state;
    return groups.map(group => ({
      label: group.name,
      value: group.name
    }));
  };

  selectOnChangeCallback = response => {
    // eslint-disable-next-line no-console
    console.log('selectOnChangeCallback', response);
  };

  handleSubmit = (values,) => {
    const { onSuccess } = this.props;
    // same shape as initial values
    console.log(values);
    onSuccess(values);
  };

  render() {
    const { type, groups } = this.state;
    const selectData = this.mapListGroupToSelect();
    const togglePassword = type === 'password' ? 'fa fa-eye fa-lg' : 'fa fa-eye-slash fa-lg';
    const classes = `${togglePassword}`;
    return (
      <Fragment>
        <Formik
          initialValues={INITAIL_VALUES}
          validationSchema={UserValidationSchema}
          onSubmit={this.handleSubmit}
        >
          {({ errors, touched }) => (
            <Form>
              <div className="col-7">
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Username</span>
                    <span className="text-danger">*</span>
                  </label>
                  <Field name="username" type="text" className="form-control rounded-0" />
                  {errors.username && touched.username ? (
                    <div className="text-danger">{errors.username}</div>
                  ) : null}
                </div>
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Email</span>
                  </label>
                  <Field name="email" type="email" className="form-control rounded-0" />
                  {errors.email && touched.email ? (
                    <div className="text-danger">{errors.email}</div>
                  ) : null}
                </div>
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Password</span>
                    <span className="text-danger">*</span>
                  </label>
                  <div className="d-flex align-items-center">
                    <Field type={type} name="password" className="form-control rounded-0 mr-2" />
                    <span className={classes} onClick={this.togglePasswordMask} />
                  </div>
                  {errors.password && touched.password ? (
                    <div className="text-danger">{errors.password}</div>
                  ) : null}
                </div>
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Confirm Password</span>
                    <span className="text-danger">*</span>
                  </label>
                  <Field name="confirmPassword" type={type} className="form-control rounded-0" />
                  {errors.confirmPassword && touched.confirmPassword ? (
                    <div className="text-danger">{errors.confirmPassword}</div>
                  ) : null}
                </div>
                <div className="my-3">
                  <label>
                    <span className="font-weight-bold">Select Group</span>
                    <span className="text-danger">*</span>
                  </label>
                  <ReactSelect
                    isMulti={false}
                    options={selectData}
                    onChangeCallback={this.selectOnChangeCallback}
                  />
                </div>
              </div>
              <button type="submit" className="btn btn-primary rounded-0 float-right mt-5 b-2">
                <span className="mx-2">Create User</span>
              </button>
            </Form>
          )}
        </Formik>
      </Fragment>
    );
  }
}

export default ViewUser;


Currently, I can access only the values from FORMIK, but I want to add the information of react select to the values, so I can display a nice message with the appropriate information each time I create a user.

I try something like:

<Field 
  component={({field, form}) =>
    <ReactSelect
      isMulti={false}
      options={selectData}
      value={selectData ? selectData.find(option => option.value === field.value) : ''}
      onChange={(option) => form.setFieldValue(field.name, option.value)}
      onBlur={field.onBlur}
    />} 
/>

Haven't tested it (and there should be cleaner ways of doing this - if it works)

I would update the answer once I have enough time to test anyways

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM