Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-select custom heading

Tags:

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

like image 805
Nerius Jok Avatar asked Oct 15 '19 10:10

Nerius Jok


People also ask

How do you style select options in react?

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.

How do I change the placeholder in react-select?

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.

How do I select a className in react JS?

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.


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.

like image 195
Laura Avatar answered Nov 15 '22 09:11

Laura