Fork me on GitHub
#reagent
<
2021-10-28
>
JB Seo13:10:05

Hello all. Reagent's `reagent.core/children` does not work with functional component. 😞 fortunately, as `reagent.core/current-component` returns mocking object, I write a helper function like below:

(defn get-children [^js this]
  (if (.-props this)
    (reagent.core/children this)
    (when-some [v (.-argv this)]
      (reagent.impl.component/extract-children v))))
Can I safely use it for functional component? for example
(defmacro nest-children []
  `(some->> (reagent.core/current-component)
            (get-children)
            (into [:<>])))

(defn fn-comp [{:keys [prop1]}]
  [:div
   (str "Prop1 is " prop1)
   (nest-children)])

(defn demo []
  [:f> fn-comp
   {:prop1 "hello"}
   [:span "world"]
   [:span "foo"]
   [:span "bar"]])
It seems work for simple tests. The reason I wrote nest-children is that basic solution like below is verbose and seems ugly to me. (especially, parameter declaration part is not good in terms of readability.)
(defn fn-comp [{:keys [prop1
                       prop2
                       on-change-prop1]} & children]
  [:div
    (when (seq children)
      (into [:<>] children]))])
Or any better solution to write nest-children without macro? Thanks.

p-himik13:10:56

I'd argue that & children in the function signature makes it much more clear that the component expects some children. I'd definitely prefer that to an implicit children passing. Also, you don't need that [:<>] or checking that there are children:

(-> [:div]
    (into children))

JB Seo14:10:30

Yes, they are optional. length check and [:<>] was for easy CSS styling.

JB Seo14:10:01

I agreed that declaring it in signature should be preferred and used to stick to it. But for container components that only have style / class props and children (like those of styled-component), nest-children is easy and handy 🙂