Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send the value as string when selecting the option

I am using react-select for autocomplete and option related field. When i select the option it passes whole that option object as {value: 'abc', label: 'ABC'} but i wanted only to pass the value as a string not the object. Thus, i used getOptionValue but it is not working as expected.

This is what I have done

<Field
  name='status'
  component={SearchableText}
  placeholder="Search..."
  options={status}
  styles={styles}
  getOptionLabel={option => option.label}
  getOptionValue={option => option.value}
/>

I have used both getOptionLabel and getOptionValue but is still passing the selected option in object form instead of just the value as string.

Expected one

status: 'active'

Current behavior

status: { value: 'active', label: 'Active'}
like image 868
Serenity Avatar asked Mar 17 '26 22:03

Serenity


1 Answers

I couldn't find getOptionValue in the docs for react-select, but you could always create an adapter around react-select. i.e. create your own Select component that uses react-select's Select component internally. After doing this it becomes possible to create your own getOptionValue. You can use this to make sure the value is a string.

import React from "react";
import Select from "react-select";

class MySelect extends React.Component {
  getSelectValue() {
    return this.props.options.find(
      option => this.props.getOptionValue(option) === this.props.input.value
    );
  }

  render() {
    console.log("value", this.props.input.value);
    return (
      <Select
        value={this.getSelectValue()}
        onChange={option => {
          this.props.input.onChange(this.props.getOptionValue(option));
        }}
        options={this.props.options}
      />
    );
  }
}

MySelect.defaultProps = {
  getOptionValue: v => v
};

const MyForm = reduxForm({ form: "MyForm" })(
  class extends React.PureComponent {
    render() {
      return (
        <Field
          name="myCoolSelect"
          component={MySelect}
          options={[
            { value: "chocolate", label: "Chocolate" },
            { value: "strawberry", label: "Strawberry" },
            { value: "vanilla", label: "Vanilla" }
          ]}
          getOptionValue={option => option.value}
        />
      );
    }
  }
);

The above is a basic example of how to get this working. You may want to pass other input or meta props to take advantage of other redux-form features. e.g. onBlur, onFocus, etc. You can see it in action here: https://codesandbox.io/s/6wykjnv32n

like image 173
Ben Lorantfy Avatar answered Mar 20 '26 12:03

Ben Lorantfy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!