Skip to content

Instantly share code, notes, and snippets.

@marcelocra
Last active August 16, 2020 01:43
Show Gist options
  • Save marcelocra/7db25bbb7449aca86e04e831f0c45e0b to your computer and use it in GitHub Desktop.
Save marcelocra/7db25bbb7449aca86e04e831f0c45e0b to your computer and use it in GitHub Desktop.
How to use goog.style/installSafeStyleSheet in Clojure, with garden.
(ns ^:figwheel-hooks dynamic-css.core
(:require
[goog.dom :as gdom]
[goog.style :as gstyle]
[reagent.core :as r]
[reagent.dom :as rdom]
[garden.core :refer [css]])
(:import [goog.html SafeStyleSheet]
[goog.string Const]))
(defonce db (r/atom {}))
(defn random-uuid-str []
(->> (random-uuid)
(str)))
(defonce class {:container (random-uuid-str)
:stuff (random-uuid-str)})
(defn install-styles! []
(gstyle/installSafeStyleSheet
(SafeStyleSheet/fromConstant
(Const/from
(css [(->> (:container class)
(str ".")
(keyword)) {:color 'red}
[:&:hover {:color 'blue}]])))))
(defn app []
[:h1 {:class (:container class)} 'hey])
(defn mount []
(do
(swap! db assoc :styles (install-styles!))
(rdom/render [app] (gdom/getElement "app"))))
(defonce init (mount))
(defn ^:before-load before-reload []
(gstyle/uninstallStyles (:styles @db)))
(defn ^:after-load reload []
(mount))
@marcelocra
Copy link
Author

This installs and removes the style block as Figwheel reloads. The uuid was my first try for some "scope".

Sometimes this doesn't work and I believe it is because installSafeStyleSheet can be loading the css after reagent's render, causing the styles to not be applied.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment