Reputation: 176
I am using react-select to show a list of users in a dropdown. I want it to always show the selected element as the first element in the list. Is there native support for this?
Example:
In the following image, since Green
is selected, I want Green
to appear at the top of the list before Ocean
Upvotes: 2
Views: 8020
Reputation: 81370
You can pass an initialize callback to useState
to sort the options
array for the first time and put the defaultValue
on top:
function sortOptions(options, selectedValue) {
return options.sort((a, b) => {
if (a === selectedValue) return -1;
if (b === selectedValue) return 1;
return 0;
});
}
const defaultValue = colourOptions[5];
const [options, setOptions] = React.useState(() =>
sortOptions(optionsProp, defaultValue)
);
return (
<Select
defaultValue={defaultValue}
onChange={(value) => setOptions(sortOptions(optionsProp, value))}
name="colors"
options={options}
/>
);
Upvotes: 0
Reputation: 51
Try this Code :
const [options, setOptions] = useState([
{ label: "Blue", value: "Blue" },
{ label: "Red", value: "Red" },
{ label: "Yellow", value: "Yellow" },
{ label: "Green", value: "Green" },
{ label: "Pink", value: "Pink" },
{ label: "White", value: "White" },
{ label: "Brown", value: "Brown" }
]);
const [value, setValue] = useState("Select");
function handler(e) {
setValue(e);
let newOptions = [];
newOptions.push({ label: e, value: e });
for (let i in options) {
if (options[i].value !== e) {
newOptions.push(options[i]);
}
}
setOptions(newOptions);
}
return (
<div className="App">
<Select
name="colors"
defaultValue={value}
options={options}
onChange={(e) => handler(e.value)}
/>
</div>
);
Click this link to view demo
Upvotes: 1