Using Radium with Reagent

I came across this StackOverflow question regarding Radium with Reagent.

Radium is a set of tools to manage inline styles on React elements. It gives you powerful styling capabilities without CSS. Inspired by React: CSS in JS by vjeux.

First thing I had to do with was to package up Radium for cljsjs/packages. By now I have enough experience in packaging up React components using Webpack for UMD consumption. This now lives as cljsjs.radium.

Next, I had to figure out how to use Radium from ClojureScript. In the examples, Radium seemed to be heavily using ES2016 decorators. Luckily they also had support for React.createClass based versions.

Below is a simple example of using Radium with Reagent

(ns rera.core
  (:require [reagent.core :as reagent]

(def Radium js/Radium)

(def styles {:base {:color "#fff"
                    ":hover" {:background "#0A8DFF"}}
             :primary {:background "#0074D9"}
             :warning {:background "#FF4136"}})

(defn button
  (let [kind (keyword (:kind data))]
     {:style (clj->js [(:base styles)
                       (kind styles)])}
     (:children data)]))

(def btn (Radium. (reagent/reactify-component button)))

(def rbtn (reagent/adapt-react-class btn))

(defn hello-world
   [rbtn {:kind :primary} "Hello Primary"]
   [rbtn {:kind :warning} "Hello Warning"]])

 (. js/document (getElementById "app")))

This example shows how easy is to use the hover css property in a React component. To do with with plain React or Reagent, isn’t trivial without resorting to a CSS file.

The key thing is that I converted a Reagent button component to a React component (using reagent/reactify-component), then passed it through Radium and then converted it back to something which I consume in reagent (using reagent/adapt-react-class).

This example is also in a GitHub repository here.

Till next time!