React-select does not show the selected value in the field

user7334203 picture user7334203 · Apr 6, 2017 · Viewed 23.7k times · Source

i have a react-select component which i define like this:

<Select
            id="portf"
            options={opts}
            onChange={value => portfolioSelector(value)}
            placeholder="Select Portfolio"
          />

with opts = [{label: any, value:1}, {label:Two, value:2}].

The values when selected are stored in the state via portfolioSelector function. The problem is that when i select a value it wasn't show in the select field. My main component is this:

const PortfolioSelector = ({
  opts,
  portfolioSelector
}) => {
  if (opts) {
    return (
      <div className="portfolio select-box">
        <label htmlFor="selectBox" className="select-box__label">
        Portfolio
        </label>
        <div className="select-box__container">
          <Select
            id="portf"
            options={opts}
            onChange={value => portfolioSelector(value)}
            placeholder="Select Portfolio"
          />
        </div>
        <div className="separator" />
      </div>
    );
  }
  return (
    <div>Loading</div>
  );
};

Do you know why?

Answer

mkaya387 picture mkaya387 · May 26, 2020

This is an alternative solution that i used.

Demo: https://codesandbox.io/s/github/mkaya95/React-Select_Set_Value_Example

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

export default function App() {
  const [selectedOption, setSelectedOption] = useState("none");
  const options = [
    { value: "none", label: "Empty" },
    { value: "left", label: "Open Left" },
    { value: "right", label: "Open Right" },
    {
      value: "tilt,left",
      label: "Tilf and Open Left"
    },
    {
      value: "tilt,right",
      label: "Tilf and Open Right"
    }
  ];
  const handleTypeSelect = e => {
    setSelectedOption(e.value);
  };

  return (
    <div>
      <Select
        options={options}
        onChange={handleTypeSelect}
        value={options.filter(function(option) {
          return option.value === selectedOption;
        })}
        label="Single select"
      />
    </div>
  );
}