somerandomusername
somerandomusername

Reputation: 2023

Retrieve tailwind/nativewind theme colors defined in global.css from javascript

I'm using expo react-native with nativewind. My theme is defined in tailwind.config.js:

module.exports = {
  darkMode: 'class',
  content: ['./app/**/*.{ts,tsx}', './components/**/*.{ts,tsx}'],
  presets: [require('nativewind/preset')],
  theme: {
    extend: {
      colors: {
        border: 'var(--border)',
        input: 'var(--input)',
        ring: 'var(--ring)',
        background: 'var(--background)',
        foreground: 'var(--foreground)',
        primary: {
          DEFAULT: 'var(--primary)',
          foreground: 'var(--primary-foreground)',
        },

It pulls in color variables from global.css

@layer base {
    :root {
        --background: hsl(0, 0%, 0%);
        --foreground: hsl(0, 0%, 98%);
        --card:hsl( 240 10% 3.9%);
        --card-foreground:hsl( 0 0% 98%);
        --popover:hsl( 240 10% 3.9%);
        --popover-foreground:hsl( 0 0% 98%);

I can't quite figure out how to get these values to use them in my code. They are available in className as "text-primary".

Most results suggest that I need to do something like this:

import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from 'path/to/your/tailwind.config.js'

const fullConfig = resolveConfig(tailwindConfig)

But this resolves in having fullConfig.theme.colors.border equaling 'var(--border)'

Upvotes: 1

Views: 1151

Answers (1)

oliverwebr
oliverwebr

Reputation: 627

You can't use .css in expo (to my knowledge). The default way to create styles in expo is StyleSheet.create.

So i would rather recommend to set the color values in the tailwind config json. The resolveConfig utility function just gives you the extended theme config: your config + base config from tailwind.

If you for some reason need to go via css you can get the values at runtime with e.g.

getComputedStyle(document.documentElement)
    .getPropertyValue('--my-css-variable');

Upvotes: -1

Related Questions