Explicit nils
As stated in the guide to Replicant flavored hiccup, explicit
nils in place of missing child nodes can sometimes be beneficial. Because
Replicant expects your hiccup to be produced by code, it uses nils to
understand how two versions of the same node relate. Let’s illustrate with an
example.
Imagine this function:
(defn render-greeting [{:keys [user]}]
[:div
[:h1 "Hello Clojure enthusiast!"]
(when user
[:p "Nice to see you, " (:user/given-name user)])
[:p "Hope all is well today!"]])
If we render this twice, first without a user, then with a user, we would produce the two following snippets of hiccup:
;; The first call with explicit nil
[:div
[:h1 "Hello Clojure enthusiast!"]
nil
[:p "Hope all is well today!"]]
;; The second call with explicit nil
[:div
[:h1 "Hello Clojure enthusiast!"]
[:p "Nice to see you, Christian"]
[:p "Hope all is well today!"]]
When rendering the second snippet, Replicant will know to insert a new node
between the h1 and the p containing “Hope all is well today!”. Contrast that
with leaving out the nil:
;; The first call without explicit nil
[:div
[:h1 "Hello Clojure enthusiast!"]
[:p "Hope all is well today!"]]
;; The second call without explicit nil
[:div
[:h1 "Hello Clojure enthusiast!"]
[:p "Nice to see you, Christian"]
[:p "Hope all is well today!"]]
In this case, Replicant wil perform a different set of operations:
- Change the text of the first
pfrom"Hope all is well today!"to"Nice to see you, Christian" - Create a new
pelement with the text"Hope all is well today!" - Insert the new
pat the end
This happens because elements are not keyed on their content, thus Replicant
concludes that the new structure has a new p element at the end. Normally this
isn’t a problem, but if you have CSS transitions or life-cycle events on any of
these nodes, the difference would be noticable.
Using explicit nils to stand in for failed conditionals and similar situations
helps Replicant make better decisions.
Note that you could achieve the same effect without the explicit nil by adding
:replicant/key to the last p. Explicit nils reduce the
need for manual keying.