Last active
August 16, 2020 01:43
-
-
Save marcelocra/7db25bbb7449aca86e04e831f0c45e0b to your computer and use it in GitHub Desktop.
How to use goog.style/installSafeStyleSheet in Clojure, with garden.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.