Skip to content

Commit

Permalink
Merge pull request #352 from reagent-project/hiccup-fragment
Browse files Browse the repository at this point in the history
Implement :<> hiccup tag for fragments
  • Loading branch information
Deraen authored Apr 3, 2018
2 parents 450a9a7 + 87b6147 commit 54d9b8e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
16 changes: 14 additions & 2 deletions src/reagent/impl/template.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
[reagent.debug :refer-macros [dbg prn println log dev?
warn warn-unless]]))

(declare as-element)

;; From Weavejester's Hiccup, via pump:
(def ^{:doc "Regular expression that parses a CSS-style id and class
from a tag name."}
Expand Down Expand Up @@ -342,6 +344,15 @@
($! jsprops :key key))
(react/createElement c jsprops)))

(defn fragment-element [argv]
(let [props (nth argv 1 nil)
hasprops (or (nil? props) (map? props))
jsprops (convert-prop-value (if hasprops props))
first-child (+ 1 (if hasprops 1 0))]
(when-some [key (key-from-vec argv)]
(oset jsprops "key" key))
(make-element argv react/Fragment jsprops first-child)))

(defn adapt-react-class
([c {:keys [synthetic-input]}]
(let [on-update (:on-update synthetic-input)
Expand Down Expand Up @@ -383,8 +394,6 @@
s
(aset tag-name-cache x (parse-tag x))))

(declare as-element)

(defn native-element [parsed argv first]
(let [comp ($ parsed :name)
synthetic-input ($ parsed :syntheticInput)]
Expand Down Expand Up @@ -429,6 +438,9 @@
(let [tag (nth v 0 nil)]
(assert (valid-tag? tag) (hiccup-err v "Invalid Hiccup form"))
(cond
(keyword-identical? :<> tag)
(fragment-element v)

(hiccup-tag? tag)
(let [n (name tag)
pos (.indexOf n ">")]
Expand Down
36 changes: 35 additions & 1 deletion test/reagenttest/testreagent.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@
(is (= 2 @ran)))))

(defn as-string [comp]
(server/render-to-string comp))
(server/render-to-static-markup comp))

(deftest to-string-test []
(let [comp (fn [props]
Expand Down Expand Up @@ -1125,3 +1125,37 @@
(fn [c div]
(is (= "parent,child,bar"
(.-innerText div))))))


(deftest test-fragments
(when (>= (js/parseInt react/version) 16)
(testing "Fragment as array"
(let [comp (fn []
#js [(r/as-element [:div "hello"])
(r/as-element [:div "world"])])]
(is (= "<div>hello</div><div>world</div>"
(as-string [comp])))))

(testing "Fragment element, :<>"
(let [comp (fn []
[:<>
[:div "hello"]
[:div "world"]
[:div "foo"] ])]
(is (= "<div>hello</div><div>world</div><div>foo</div>"
(as-string [comp])))))

(testing "Fragment key"
;; This would cause React warning if both fragements didn't have key set
(let [comp (fn []
[:div
(list
[:<>
{:key 1}
[:div "hello"]
[:div "world"]]
^{:key 2}
[:<>
[:div "foo"]])])]
(is (= "<div><div>hello</div><div>world</div><div>foo</div></div>"
(as-string [comp])))))))

0 comments on commit 54d9b8e

Please sign in to comment.