Reputation: 4460
Is there any way to change the selected value component design, At my option menu, I show CscId and CscDesc but when I select the option, I only want to show CscId only. Is there any way to change the selected value component? I google for this one and it already took 1 day. Please Help me.
Here is my react-select
import React from "react";
import Select from 'react-select';
const costcenterselect = ({ value, onChange, id, datasource }) => {
const formatOptionLabel = ({ CscID, CscDesc }) => (
<div style={{ display: "flex"}}>
<div style={{width:'40%'}}>{CscID}</div>
<div>{CscDesc}</div>
</div>
);
return (
<div>
<Select
id={id}
menuIsOpen={true}
formatOptionLabel={formatOptionLabel}
getOptionValue={option => `${option.CscID}`}
options={datasource}
onChange={onChange}
defaultValue={value}
/>
</div>
)
}
export default costcenterselect;
Upvotes: 6
Views: 6307
Reputation: 1083
You can do it using formatOptionLabel
itself. It has a second argument which provides you with meta information like context
which you can use to conditionally render. Here is a working demo.
You can see that context === value
allows you to render for selected value while context === menu
renders for the options.
const formatOptionLabel = ({ CscID, CscDesc }, { context }) => {
if (context === "value") {
return <div>{CscID}</div>;
} else if (context === "menu") {
return (
<div style={{ display: "flex" }}>
<div style={{ width: "40%" }}>{CscID}</div>
<div>{CscDesc}</div>
</div>
);
}
};
Upvotes: 17