Add reactify-component: adapts Reagent component for use in JSX

This commit is contained in:
Dan Holmsand 2015-02-08 00:01:31 +01:00
parent b574d8cc5a
commit 8b5905c9e1
3 changed files with 41 additions and 0 deletions

View File

@ -49,6 +49,13 @@ just like a Reagent component function or class in Hiccup forms."
[c]
(tmpl/adapt-react-class c))
(defn reactify-component
"Returns an adapter for a Reagent component, that may be used from
React, for example in JSX. A single argument, props, is passed to
the component, converted to a map."
[c]
(comp/reactify-component c))
(defn render
"Render a Reagent component into the DOM. The first argument may be
either a vector (using Reagent's Hiccup syntax), or a React element. The second argument should be a DOM node.

View File

@ -212,3 +212,16 @@
(str " (in " n ")")
""))
""))
(defn shallow-obj-to-map [o]
(into {} (for [k (js-keys o)]
[(keyword k) (aget o k)])))
(defn reactify-component [comp]
(.' js/React createClass
#js{:displayName "react-wrapper"
:render
(fn []
(this-as
this (as-element
[comp (shallow-obj-to-map (.' this :props))])))}))

View File

@ -471,3 +471,24 @@
(rstr [d2 {:class "foo"} "a"])))
(is (= (rstr [:div "a" "b" [:div "c"]])
(rstr [d2 "a" "b" [:div "c"]])))))
(deftest test-reactize-component
(let [ae reagent/as-element
ce reagent/create-element
c1r (fn [p]
[:p "p:" (:a p) (:children p)])
c1 (reagent/reactify-component c1r)]
(is (= (rstr [:p "p:a"])
(rstr (ce c1 #js{:a "a"}))))
(is (= (rstr [:p "p:"])
(rstr (ce c1 #js{:a nil}))))
(is (= (rstr [:p "p:"])
(rstr (ce c1 nil))))
(is (= (rstr [:p "p:a" [:b "b"]])
(rstr (ce c1 #js{:a "a"}
(ae [:b "b"])))))
(is (= (rstr [:p "p:a" [:b "b"] [:i "i"]])
(rstr (ce c1 #js{:a "a"}
(ae [:b "b"])
(ae [:i "i"])))))))