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

5.4k Views Asked by At

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...

  • Imported the package... npm install --save-dev postcss-import-json

  • Created a JSON file called 'masterConfig.json'

  • Imported the above file into my main stylesheet using the name i've called my colour (primary)... :root { @import-json "../Assets/MasterConfig/masterConfig.json" (primary); }

  • Added the above colour name to my list of colours... :root {primary: primary} I've also tried this with the -- prefix by changing to @import-json... (primary as primary prefix --)

  • ...and added it in my code where it is to be used... style={{background: "var(--primary)"}} ^^^ with and without the prefix

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!

2

There are 2 best solutions below

0
On BEST ANSWER

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!

1
On

There appears to be two was to access the variable you've defined, I've done it in two separate ways and you can implement whichever makes your code neater!

Referencing the variable inline:


CSS

:root {
    --testcolor: red;
}


HTML

<div style="background:var(--testcolor)">
    Many words
</div>

Example of the working product in JS Fiddle: https://jsfiddle.net/ta37nzer/


Accessing the variable through a class:


CSS

:root {
    --testcolor: red;
}
.exampleClass {
    background: var(--testcolor);
}


HTML

<div class="exampleClass">
    Many words
</div>

Example of the working product in JS Fiddle: https://jsfiddle.net/ta37nzer/1/