Last active
October 19, 2015 08:30
-
-
Save petterik/5e921fd2c324a3848f96 to your computer and use it in GitHub Desktop.
Wasn't impressed with react's camel case css...
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
;; Garden style css (just uses css properties as keywords as you'd expect): | |
[:style (css {:border-width "1px"})] | |
;; React cljs (camel cased css property names): | |
[:div {:style #js {:borderWidth "1px"}}] | |
;; Why camel case? "[...] This is consistent with the DOM style JavaScript property", see: https://facebook.github.io/react/docs/dom-differences.html | |
;; Problem: Cannot share code between inline css and react. | |
;; Solution: Create a function which takes a css map and returns whatever react wants. | |
;; Now with our created function "(style ..)" | |
;; inline css: | |
[:style (css {:border-width "1px"})] | |
;; React: | |
[:div (style {:border-width "1px"})] | |
;; Which means I can share code! | |
(let [css-map {:border-width "1px"} | |
[:div | |
[:style (css css-map)] | |
[:div (style css-map)]]) | |
;; Implementation of style: | |
(ns your.namespace.foo | |
(:require | |
[clojure.string :as s] | |
[clojure.walk :as w])) | |
(defn camelCase [k] | |
(when (namespace k) | |
(throw (str "cannot camelCase a keyword with a namespace. keyword=" k))) | |
(let [[a & xs] (s/split (name k) "-")] | |
(s/join (cons a (map s/capitalize xs))))) | |
(defn style [css-map] | |
{:style (->> css-map | |
(w/postwalk #(if (keyword? %) (camelCase %) %)) | |
(clj->js))}) | |
;; To make it fast(er): | |
;; 1. Can memoize call to camel-case since keys are limited to css properties | |
;; 2. Make style a macro, so that the css is generated at compile time. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment