How to set custom component for selected value with react select, i was able to customize options but how about selected option itself, would be smart to have the same selected component as options too, any ideas?
<Select
components={{ Option: CustomOption }}
options={options}
styles={customStyles}
/>;
Component:
const CustomOption = ({ value, label, innerProps, innerRef }) => (
<div ref={innerRef {...innerProps}>
<img src={label === 'En' ? pngEn : label === 'Ru' ? pngRu : pngLt} />
<div>{label}</div>
</div>
);
Edit, options bellow, i want to the flag would be seen then option is selected, thats probably because of custom options:
const options = [
{ value: "lt", label: "Lt" },
{ value: "en", label: "En" },
{ value: "ru", label: "Ru" },
];
To style react-select drop down options, we can create an object with the styles we want to apply and set that as the value of the styles prop. We create the colourStyles object with the control method that return an object with the styles. And we have the option method that returns the styles for the options.
Set the first option element of the select tag to disabled and give it an empty string value. Initialize the state for the select tag to an empty string.
className. To specify a CSS class, use the className attribute. This applies to all regular DOM and SVG elements like <div> , <a> , and others. If you use React with Web Components (which is uncommon), use the class attribute instead.
I think the easiest way to do it is to use a custom Option
component exactly the way you did and storing an extra props inside your options
to have the corresponding picture you want to display.
Below an example with react-icons
library instead of using an image but the idea is the same:
const Option = props => {
const CComponent = props.data.icon;
return (
<div style={{ display: "flex" }}>
<CComponent />
<components.Option {...props} />
</div>
);
};
const options = [
{ label: "Option 1", value: 1, icon: FaOpera },
{ label: "Option 2", value: 2, icon: FaFirefox },
{ label: "Option 3", value: 3, icon: FaInternetExplorer }
];
function App() {
return (
<div className="App">
<Select options={options} components={{ Option }} />
</div>
);
}
Live example here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With