5

I am converting styles of my app from Less to Emotion

in Less I have styles as follows:

@blue: #476882;
background: rgba(red(@blue), green(@blue), blue(@blue), 0.5);

while converting to Emotion I am doing this:

export const BLUE = '#476882'
background: rgba(red(${BLUE}), green(${BLUE}), blue(${BLUE}), 0.5);

however it is not working.

enter image description here

any suggestions to make this work?

seven-phases-max
  • 11,765
  • 1
  • 45
  • 57
Rahul Yadav
  • 2,627
  • 5
  • 30
  • 52
  • All IDEs has this as default, or as a plugin. Try that, good luck (Color Picker) – Modig Jan 31 '18 at 12:42
  • 1
    Instead of this: background: rgba(red(${BLUE}), green(${BLUE}), blue(${BLUE}), 0.5); Try: background: rgba(${RED},${GREEN},${BLUE}, 0.5); – RacoonOnMoon Jan 31 '18 at 14:43
  • 1
    I have the hex color `BLUE`and I dont want to create 3 variables `RED, GREEN and BLUE` – Rahul Yadav Feb 01 '18 at 06:57
  • Will `background-color:${BLUE}; opacity:0.5` work for you? – Mr Lister Feb 01 '18 at 13:09
  • Possible duplicate of [How to convert HEX color to rgba with Less compiler?](https://stackoverflow.com/questions/14860874/how-to-convert-hex-color-to-rgba-with-less-compiler) –  Feb 02 '18 at 08:45

2 Answers2

2

I couldn't find any method within emotion, but I personally solved it with an utility function that uses the hex-rgb package:

import hexRgb from 'hex-rgb';

export const rgba = (hex, alpha) => {
  const rgb = hexRgb(hex, { format: 'array' })
    .slice(0, -1)
    .join(',');
  return `${rgb},${alpha}`;
};

and then just use it like so: rgba(${rgba('#000', 0.15)})

alliuca
  • 396
  • 2
  • 13
0

The simple converter, without any dependencies.

export const hexToRgba = (hex: string, alpha: string | number): string => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

  return result
    ? `rgba(${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(
        result[3],
        16,
      )}, ${alpha})`
    : hex;
};