Reputation: 9790
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>
);
}
Upvotes: 0
Views: 5465
Reputation: 117
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>
);
Upvotes: 2
Reputation: 1105
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)}
/>
Upvotes: 0