Zormi
Zormi

Reputation: 113

How to style each option of react-select component differently?

I'm using react-select v2 (2.41). I have 3 options set and I want to set background color of each option to different color. Is this possible and how?

I've tried with styles like this:

const customStyle = {
    option: (base, state) => ({
        ...base,
        backgroundColor: "red",
    })
};
<Select
    ...
    options={options}
    styles={customStyle}
 />

but this changes color of all options to the same color. What I want is for each option to have different background color. Something like this:

enter image description here

Upvotes: 3

Views: 5917

Answers (3)

ronara
ronara

Reputation: 366

One more way to achieve what you are trying to do is with react select styles

documentation: https://react-select.com/styles

example:

const colorsArray = [
    { label: "Option 1", value: 1, color: '#FF8B8B' },
    { label: "Option 1", value: 2, color: '#ABFF8B' },
    { label: "Option 1", value: 3, color: '#80CEAC' },
];

const colorStyles = {
    option: (styles, { data }) => {
        return {
            ...styles,
            backgroundColor: data.color,
        };
    },
};

<Select
    value={colorsArray[0]}
    options={colorsArray}
    styles={colorStyles}
/>

live exmaple

Upvotes: 5

Laura
Laura

Reputation: 8630

You can use the component props to setup a background color base on your options props like this:

const Option = props => {
  return (
    <div style={{ backgroundColor: props.data.color }}>
      <components.Option {...props} />
    </div>
  );
};
const options = [
  { label: "Option 1", value: 1, color: "red" },
  { label: "Option 2", value: 2, color: "orange" },
  { label: "Option 3", value: 3, color: "green" }
];

function App() {
  return (
    <div className="App">
      <Select options={options} components={{ Option }} />
    </div>
  );
}

Like in this live example.

Upvotes: 5

mhatch
mhatch

Reputation: 4605

What about using :nth-child() CSS selector?

<Select
    ...
    className="myclass"
    classNamePrefix="myclass"
    options={options}
    styles={customStyle}
 />

// CSS
.myclass__value-container:nth-child(1) {
    // rules
}
.myclass__value-container:nth-child(2) {
    // rules
}
.myclass__value-container:nth-child(3) {
    // rules
}

Upvotes: 4

Related Questions