Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access tailwind colors from javascript

I am using ApexCharts and would like to use my tailwind colors (red-500, etc) to style my chart. I can't use css classes (so can't use theme() in a post-css context). I also can't reference the default config because I have extended it already. I could import my new config's colors, however this does not seem like a good way to do it (besides, some css classes could be generated with utilities, and would not be accessible this way). I have also theorized that I could add a hidden html element to my dom, get the css property from it and then remove, but this also seems like a bad approach.

Thanks CoffeeKing68

like image 503
CoffeeKing68 Avatar asked Apr 09 '20 09:04

CoffeeKing68


People also ask

Does tailwind CSS use JavaScript?

Tailwind CSS is written in JavaScript and distributed as an npm package, which means you've always had to have Node. js and npm installed to use it.

How do I add another color to Tailwind?

You can easily add new colors to Tailwind CSS and keep the originals ones using customization configuration. You can configure your colors under the colors key in the theme section of your tailwind. config. js file.


3 Answers

Check the official docs: https://tailwindcss.com/docs/configuration#referencing-in-java-script

You can use the built-in helper resolveConfig to get your config.

like image 200
mrp Avatar answered Oct 08 '22 08:10

mrp


@mrp's answer is great if you want to go the official route. However, I didn't want to go through the trouble of adding another babel plugin.

Instead, you can just reference their colors at https://github.com/tailwindlabs/tailwindcss/blob/master/src/public/colors.js

Then create an export in constants file i.e.

export default {
  inherit: 'inherit',
  current: 'currentColor',
  transparent: 'transparent',
  black: '#000',
  white: '#fff',
  slate: {
    50: '#f8fafc',
    100: '#f1f5f9',
    200: '#e2e8f0',
    300: '#cbd5e1',
    400: '#94a3b8',
    500: '#64748b',
    600: '#475569',
    700: '#334155',
    800: '#1e293b',
    900: '#0f172a',
  },
  ...
}

and then you can just do e.g.

import COLORS from 'constants/colors'

<Icon color={COLORS.emerald[700]} />
like image 22
Will Avatar answered Oct 08 '22 06:10

Will


You could put tailwind colors into css variables, that are accessible from JavaScript.

like image 42
jorbuedo Avatar answered Oct 08 '22 06:10

jorbuedo