cssjsonreactjspostcsspostcss-import

How can I use colours stored in JSON in my CSS?


I need to get some colour values out of a DB and use them in my CSS so that each customer has a colour branded version of my React.js application, but I'm not sure how.

I have other elements of branding such as logos, slogans and terminology which I'm pulling out of the DB, storing as a JSON file, and referencing around the site, which works fine, but the problem is the colours which I need to use in my stylesheet as I need to use the pseudo classes that CSS offer.

I've found this postcss-import-json package which claims to do this, but I can't seem to get it to work as intended.

So far I've...

Am I doing something wrong? I've noticed in the example it uses the $ symbol, so can this only be used with SCSS?

Any help with this, or any other way to achieve this would be great, thanks!


Solution

  • So, I was quite surprised that I didn't already know how to do this, it seems so trivial and doesn't need any additional package.

    To change a CSS varibale from JavaScript code, simply target the root element as you normally would, and set the property!

    CSS


    Create a variable (I'm using a fallback colour)

    :root {--primary: #123456;}

    JavaScript


    I'm using React, and set this is my App.js componentDidMount function so it's global to my app. I've hard-coded the colour, but this can be pulled from the DB.

    componentDidMount() {
    const root = document.documentElement;
    
    root.style.setProperty('--primary', '#CCCC00');
    }
    

    BooYaa!