'show default value in select input with backgroundcoulr different for each : react js

i have some select buttons displayed dynamicaly based on the user.subscription the values in user.subscription can be 2 monthpack , 3 month pack, 6month pack, 12month pack,

so the value in user.subscription` sould be selected as default when the maping loads in all

also there must be differt colours for backgound of the slected button based on the default select button button

if

2 month package is the default seleted then defaultcolor should be red

if

3 month package is the default seleted then defaultcolor should be green

if

6 month package is the default seleted then defaultcolor should be yellow

if

12 month package is the default seleted then defaultcolor should be orange

{
  data.map((user) => (
    <select
      value={user.subscription}
      style={{ background: defaultcolor }}
      onChange={handleBackground}
    >
      <option value="white"> 2 month package</option>
      <option value="green">3 month package</option>
      <option value="red">6 month package</option>
      <option value="yellow">12 month package</option>
    </select>
  ));
}


Solution 1:[1]

you can hold a small 'configuration' object like this:

const monthToColor = {
  2: 'red',
  3: 'green',
  6: 'yellow',
  12: 'orange'
}

The keys should match the user.subscription options you have.

Now, for each option, add a style with background color of: monthToColor[user.subscription] like this:

<option style={{ backgroundColor: monthToColor[user.subscription] }}>
  months
</options>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GiL Itzhaky