DEV Community

Artur Czemiel
Artur Czemiel

Posted on

CSS in JS -> write your own engine

The why?!

Nowadays advanced frameworks like React, Vue, Angular, etc. are using CSS in JS syntax. You should write your own CSS in JS minimal engine to understand what's going on under the hood.

Javascript

function o2s(o, className) {
  var elm = new Option();
  Object.keys(o).forEach(function() {
    (elm.style)[a] = o[a];
  });
  return `.${className}{\n${elm.getAttribute("style")}\n}`;
}
/**
 * Class responsible for small css functionalities rendered in HTML like menu
 *
 * @export
 * @class CSSMiniEngine
 */
export class CSSMiniEngine {
  classes = [];
  /**
   * add css class with css params
   *
   * @memberof CSSMiniEngine
   * @param {Partial<CSSStyleDeclaration>} o
   * @param {string} className
   */
  addClass = (o, className) => {
    this.classes.push(o2s(o, className));
  };
  /**
   * compile to style tag in head
   *
   * @memberof CSSMiniEngine
   */
  compile = () => {
    const head = document.head || document.getElementsByTagName("head")[0];
    const style = document.createElement("style");
    head.appendChild(style);
    style.type = "text/css";
    style.appendChild(document.createTextNode(this.classes.join("\n")));
  };
}

Enter fullscreen mode Exit fullscreen mode

Typescript

function o2s(o: Partial<CSSStyleDeclaration>, className: string) {
  var elm = new Option();
  Object.keys(o).forEach(function(a: string) {
    (elm.style as any)[a as any] = o[a as any];
  });
  return `.${className}{\n${elm.getAttribute("style")}\n}`;
}
/**
 * Class responsible for small css functionalities rendered in HTML like menu
 *
 * @export
 * @class CSSMiniEngine
 */
export class CSSMiniEngine {
  classes: string[] = [];
  /**
   * add css class with css params
   *
   * @memberof CSSMiniEngine
   * @param {Partial<CSSStyleDeclaration>} o
   * @param {string} className
   */
  addClass = (o: Partial<CSSStyleDeclaration>, className: string) => {
    this.classes.push(o2s(o, className));
  };
  /**
   * compile to style tag in head
   *
   * @memberof CSSMiniEngine
   */
  compile = () => {
    const head = document.head || document.getElementsByTagName("head")[0];
    const style = document.createElement("style");
    head.appendChild(style);
    style.type = "text/css";
    style.appendChild(document.createTextNode(this.classes.join("\n")));
  };
}

Enter fullscreen mode Exit fullscreen mode

Usage example

Instantiate

const cssEngine = new CssMiniEngine()
Enter fullscreen mode Exit fullscreen mode

Create Class

const className = "MyClass"
cssMiniEngine.addClass(
      {
        visibility: "visible",
        position: "fixed",
        background: "transparent",
        border: "0",
        textAlign: "center",
      },
      className
);

Enter fullscreen mode Exit fullscreen mode

Use it

In pure js

const div = document.createElement("div")
div.classList.add(className)

Enter fullscreen mode Exit fullscreen mode

In React

export const MyDiv = () => (
  <div className={className}>Hello</div>
)
Enter fullscreen mode Exit fullscreen mode

In the end call

cssEngine.compile()

Enter fullscreen mode Exit fullscreen mode

So it will insert all your classes to DOM as a style tag
Thank you for reading!

Top comments (0)