2

I'd like to parse a value from a variable in Javascript to a React style property.

However, it appears that one might only be able to add opacity with the rgba value?

Say I have:

const blueColor = "#2c8da9"

I now want to add that to a background color property in JSX with 0.2 opacity. I can do this with rgba, but it does not look nice:

backgroundColor: rgba(blueColor, 0.2)

Is there a way to achieve the same, directly referencing the hexidecimal value rather than using rgba, to input opacity directly into, for example, a backgroundColor property?

cbll
  • 6,499
  • 26
  • 74
  • 117
  • Have you tried this: https://stackoverflow.com/a/17239853/6638533? It may be working, I haven't tried though.. It is on android though, I don't know whether this also applies here.. – samAlvin Oct 17 '17 at 18:13
  • Turns out there is this javascript version for this (on the bottom of the answer): https://stackoverflow.com/a/25170174/6638533 – samAlvin Oct 17 '17 at 18:15
  • @samAlvin technically I could write a helper function for it, yeah, but it seems a bit overkill imo – cbll Oct 17 '17 at 18:18

2 Answers2

8

You can use the new 8 digit hex color notation, where the last two digits signify the opacity.

const blueColor = '#2c8da9';
const oBlueColor = blueColor+'33'; // 0.2 opacity added

document.getElementById('one').style.backgroundColor = blueColor;
document.getElementById('two').style.backgroundColor = oBlueColor;
<div id="one">one</div>
<div id="two">two</div>

Doesn't work on all browsers yet though, so it's OK to use only if you know your users all have compliant browsers. You might want to hold off releasing this in the wild for now.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
-1

thers are two ways to set opacity by using rgba or direct opacityy

x,.xy{opacity:0.2;}etc

  • You cannot use opacity in this case.The opacity will be set on the *entire element* and not just the background color. This is a small but important distinction if you're trying to do something like have a solid color element nested within the original element. – Lauren Apr 24 '20 at 00:12