react-select custom heading

Viewed 3963

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" },
];

enter image description here

1 Answers

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.

Related