简体   繁体   中英

react-select use label as value passed to component instead of value from options array

I am coming across a common problem when using react-select . All works well if you don't have to pass a value to the component, but in cases where you do it is quite inconvenient.

Often the value and the label will differ.

When I use the set the state using the value (as I need to) then I don't know how to show the label without having to write a function to map this. Is anything built into the library to handle this?

See link to a code sandbox here

And below is the code showing this issue more clearly. Let me know if any clarity is required?

const options = [
  {
    label: "Chelsea Fc",
    value: "CFC"
  },
  {
    label: "Man Utd Fc",
    value: "MUFC"
  }
];

function App() {
  const [team, setTeam] = useState("");

  return (
    <React.Fragment>
      <button onClick={() => setTeam("MUFC")}>Set team to Man Utd</button>
      <Select
        value={{ label: team }}
        options={options}
        onChange={item => setTeam(item.value)}
      />
    </React.Fragment>
  );
}

Try update the onChange function:

onChange={item => setTeam(item.label)}

Or add a function to get the label:

const [team, setTeam] = useState("");

const getLabel = team => {
 if (team.length > 0) {
  const selected = options.filter(option => option.value === team);
  return selected[0].label;
 }
};

return (
  <div className="App">
    <button onClick={() => setTeam("MUFC")}>Set to Man Utd</button>
    <Select
      value={{ label: getLabel(team) }}
      options={options}
      onChange={item => setTeam(item.value)}
    />
  </div>
);

I think you need to map it yourself unfortunately, react-select accepts an object into the value prop.

I'd make the following changes personally:

const [team, setTeam] = useState(options[0]); (use whatever option you want as the default team to be displayed, or null for no default)

Find the required option to set the value for:

<button
  onClick={() => setTeam(options.find(option => option.value === "MUFC"))}
>

or hardcode it:

<button
  onClick={() => setTeam(options[1])}
>

make it so that the Select uses the team from state as value, and onChange you simply set the team to the item itself

<Select
  value={team}
  options={options}
  onChange={item => setTeam(item)}
/>

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