Fork me on GitHub
#beginners
<
2023-08-19
>
Stef Coetzee12:08:40

How would one go about optionally including a map before other parameters in the definition of a variadic function? Context: Suppose one wants to call a Reagent component (let's call it component) in one of two ways, for example:

[component {:class "..."} [:h1 ...] [:p ...] ...]
or
[component [:h1 ...] [:p ...] ...]
In both cases, everything that isn't a map is considered a child of component. Defining component as:
(defn component [{:keys [class]} & args]
  [:div
   {:class (str class " "
                "other classes in default component")}
   args])
seems suboptimal, as one would have to pass {} before other parameters when calling component (otherwise the :h1 in the second example above won't render).

2
Stef Coetzee13:08:05

"Specifically, if the first argument to your Reagent function is a map, that is assigned to this.props of the underlying Reagent component. All other arguments are assigned as children to this.props.children."

Stef Coetzee13:08:41

Thus, component definition could be:

(defn component []
  (let [this (r/current-component)]
    (into [:div {:class (str (:class (r/props this))
                             " "
                             "other classes in default component")}]
          (r/children this))))