javascript - How to access values from React Select and pass them to Formik values on Submit? - Stack Overflow

I want to access my React-Select elements value and pass it as values in the OnSubmit Function and adde

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 ponent, 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 ponent:

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: []
  };

  ponentDidMount() {
    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 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 ponent, 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 ponent:

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: []
  };

  ponentDidMount() {
    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.

Share Improve this question asked Feb 8, 2019 at 12:29 user10104341user10104341
Add a ment  | 

1 Answer 1

Reset to default 5

I try something like:

<Field 
  ponent={({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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744374297a4571106.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信