Austin Gayler
Austin Gayler

Reputation: 4366

How to import global CSS from JSON in React

I have something along the lines of

  "A": {
    "color": "#FF0000"
  },
  "B": {
    "color": "#006600"
  },

being returned by an API. I want to transform this into CSS, such as

.A { color : #FF0000}
.B {...}

and then load it for global use in my application. How can I do this? All the other solutions I've found require loading from a file, or specify that you apply cssFile.class property. There are an unknown amount of styles in the JSON.

Upvotes: 0

Views: 656

Answers (1)

Joseph Marikle
Joseph Marikle

Reputation: 78560

Principally, you'll want to use for..in so you can iterate over the object properties. You'll do this for both the classes and the class properties. Then it's just a matter of building out the right syntax; adding it to a <style> element, which we'll create programmatically; and injecting that into the document <head>.

var data = {
  "A": {
    "color": "#FF0000"
  },
  "B": {
    "color": "#006600"
  }
}, rules = [];


for(var i in data) {
  var rule = `.${i}{`;
  for(var j in data[i]) {
    rule += `${j}:${data[i][j]};`;
  }
  rule += `}`;
  rules.push(rule);
}

var injectedStyles = document.createElement('style');
injectedStyles.setAttribute('type', 'text/css');
injectedStyles.innerHTML = rules.join('');

document.head.appendChild(injectedStyles);
<p class="A">This should be red</p>
<p class="B">This should be dark green</p>
<p class="C">This should be the default text color</p>

Upvotes: 1

Related Questions