Home > Enterprise >  react-select not updating selected value on initial select
react-select not updating selected value on initial select

Time:10-23

You can find the below example to see my issue: Codesandbox Demo

CodePudding user response:

import ReactDOM from "react-dom";

import "./styles.css";
import "./Department";
import React, { useState } from "react";
import Select from "react-select";

function App() {
  const guests = [
    {
      name: "Kait",
      plus: true,
      plusName: "Kitty"
    },
    {
      name: "Séanin",
      plus: true,
      plusName: "Guest"
    }
  ];

  const [region, setRegion] = useState("");

  return (
    <>
      <Select
        value={region}
        onChange={(item) => {
          console.log(item);

          setRegion(item.value.plusName);
        }}
        options={guests.map((guest, index) => {
          return {
            label: guest.name,
            value: guest,
            key: index
          };
        })}
      />
      {region}
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

The problem was what ever you set as option you will get the same in the item.

So instead of just storing the name I stored the full guest object in option.value and accordingly read it from item.value.<feild>.

  • Related