Get selected value onChange in react-select

I am using react-select package and using a custom options array to populate the data (i.e it custom labels etc.)

I have seen a couple of solutions they are not using options props to set value or just use default array pattern to populate data and set value and get it onChange, however I am unable to get value in my case:

  • If I set value prop it doesn’t let me select option

  • If I pass the same (option) => option.phaseText) onChange, it returns it as a string

    const HandelChange = (obj) => {
        console.log(obj);
    };
    const [dataPhase, setDataPhase] = useState([
        { phaseID: 1, phaseText: "Item 1" },
        { phaseID: 2, phaseText: "Item 2" },
        { phaseID: 3, phaseText: "Item 3" },
        { phaseID: 4, phaseText: "Item 4" },
        { phaseID: 5, phaseText: "Item 5" },
    ]);
    
    <Select
       isSearchable
        options={dataPhase}
        getOptionLabel={(option) => option.phaseText}
        getOptionValue={(option) => option.phaseText}
        className="diMultiSelect"
        classNamePrefix="diSelect"
        styles={styles}
        maxMenuHeight={150}
        value={(option) => option.phaseText} // this doesn't let me click options
        onChange={() => HandelChange((option) => option.phaseText)} // this returns (option) => option.phaseText) as a string
    />
    

I am new to React, surely I don’t know all, please let me know what I am doing wrong.

Thanks in advance.

Answer

you can maintain selectedValue in a state and use it.

With Hooks:

import React, { useState } from "react";
import Select from "react-select";

const UseHooksAndSelect = () => {
  const [dataPhase, setDataPhase] = useState([
    { phaseID: 1, phaseText: "Item 1" },
    { phaseID: 2, phaseText: "Item 2" },
    { phaseID: 3, phaseText: "Item 3" },
    { phaseID: 4, phaseText: "Item 4" },
    { phaseID: 5, phaseText: "Item 5" }
  ]);

  const [selOption, setSelOption] = useState({});

  const HandelChange = (obj) => {
    setSelOption(obj);
    console.log(obj);
  };

  console.log("Selected::", selOption.phaseID, selOption.phaseText);

  return (
    <Select
      isSearchable
      options={dataPhase}
      getOptionLabel={(option) => option.phaseText}
      getOptionValue={(option) => option.phaseText}
      className="diMultiSelect"
      classNamePrefix="diSelect"
      //  styles={styles}
      maxMenuHeight={150}
      value={selOption} // this doesn't let me click options
      onChange={(option) => HandelChange(option)} // this returns (option) => option.phaseText) as a string
    />
  );
};

export default UseHooksAndSelect;

With Class

Experiment here:

Edit react-select-test (forked)

import React, { Component } from "react";
import Select from "react-select";
import axios from "axios";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedValue: {},
      selectOptions: [],
      id: "",
      name: ""
    };
  }

  async getOptions() {
    const res = await axios.get("https://jsonplaceholder.typicode.com/users");
    const data = res.data;

    const options = data.map((d) => ({
      value: d.id,
      label: d.name
    }));

    this.setState({ selectOptions: options });
  }

  handleChange(e) {
    console.log(e);
    this.setState({ selectedValue: e });
  }

  componentDidMount() {
    this.getOptions();
  }

  buttonClick = () => {
    const valueToSet = this.state.selectOptions.find((row) => {
      return row.value === 2 && row.label === "Ervin Howell";
    });

    if (valueToSet) {
      this.handleChange(valueToSet);
    }
  };

  render() {
    const { selectedValue = {} } = this.state;
    console.log(this.state.selectOptions);
    return (
      <div>
        <Select
          minMenuHeight={50}
          maxMenuHeight={100}
          value={selectedValue}
          options={this.state.selectOptions}
          onChange={this.handleChange.bind(this)}
        />
        <p>
          You have selected <strong>{selectedValue.label}</strong> whose id is{" "}
          <strong>{selectedValue.value}</strong>
        </p>
        <button onClick={this.buttonClick}>Click</button>
      </div>
    );
  }
}