简体   繁体   中英

how to set value by id in react-select

I use react-select.I have a number of react-select that change the values inside the state by handleChange.And finally they are stored somewhere(To simplify, I wrote a react-select). So far no problem.

export const regionOptions = [
  { id: "1", value: "region 1", label: "region 1" },
  { id: "2", value: "region 2", label: "region 2" },
  { id: "3", value: "region 3", label: "region 3" },
  { id: "4", value: "region 4", label: "region 4" },
  { id: "5", value: "region 5", label: "region 5" },
  { id: "6", value: "region 6", label: "region 6" },
  { id: "7", value: "region 7", label: "region 7" },
  { id: "8", value: "region 8", label: "region 8" }
];

To edit the form, I want to set the react-select, but by ID.for example if State.region = 2 react-select Result = region2. tip:handleChange should not be changed . Here you can see my codeSandbox

I did some modification in the render function in your codesandbox. react-select accepts array of value and label pairs as options so you need to convert the region options to the data that react-select can accept correctly.

const tempOptions = regionOptions.map(option => ({
      value: option.id,
      label: option.label
    }));

This line is added to render function.

You can try 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"));
<Select
   options={regionOptions}
   getOptionValue={({ id }) => id}
 />

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