how to set value in react-select

Viewed 10934

how to set value by id in react-select For example, I want to select the label value according to the value of the ID. id = "2" result = "Summer"

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = { selectedOption: "" };
  }

  options = [
    { id: "1", value: "Spring", label: "Spring" },
    { id: "2", value: "Summer", label: "Summer" },
    { id: "3", value: "Autumn", label: "Autumn" },
    { id: "4", value: "Winter", label: "Winter" }
  ];

  handleChange = selectedOption => {
    this.setState({ selectedOption });
  };

  render() {
    return (
      <Select
        value={this.state.selectedOption}
        onChange={this.handleChange}
        options={this.options}
      />
    );
  }
}

Here you can see my CodeSandbox. Thank you in advance for your help and guidance

2 Answers

Please check this example:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

import Select from "react-select";

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedOption: ''
    };
  }

  options = [
    { id: "1", value: "Spring", label: "Spring" },
    { id: "2", value: "Summer", label: "Summer" },
    { id: "3", value: "Autumn", label: "Autumn" },
    { id: "4", value: "Winter", label: "Winter" }
  ];

  handleChange = selectedOption => {
    this.setState({ selectedOption });
  };

  render() {
    return (
      <div>
        <Select
          value={this.state.selectedOption}
          onChange={this.handleChange}
          options={this.options}
        />
        <button
          onClick={() => {
            let summer = this.options.find(o => o.id === "2");
            this.setState({ selectedOption: summer });
          }}
        >
          Set Summer
        </button>
      </div>
    );
  }
}

ReactDOM.render(<MyComponent />, document.getElementById("app"));

Here you can see my CodeSandbox.

react-select returns entire object {id, value, label} onChange. To set selected label value

  handleChange = selectedOption => {
    this.setState({ selectedOption: selectedOption.value }); // selected option value
  };
Related