nosco / hx

A simple, easy to use library for React development in ClojureScript.
MIT License
247 stars 16 forks source link

Helper for HoC #9

Closed lilactown closed 5 years ago

lilactown commented 5 years ago

Right now, creating components that need to be wrapped in HOC (especially multiple HOC) is a bit cumbersome.

See https://github.com/Lokeh/hx/blob/master/examples/workshop/sortable.cljs and https://github.com/Lokeh/hx/blob/master/examples/workshop/react_dnd.cljs for examples.

I could imagine an API similar to:

(hx/defnc DraggableBox [{:keys [connect-drag-source top left text] :as props}]
  ;; key `:wrap` defines a vector of HoCs to wrap the component in
  {:hx/wrap [(dnd/DragSource "box"
                       box-spec
                       ;; this maps the react-dnd context to props for our
                       ;; component
                       (fn [connect]
                         #js {:connectDragSource (. connect dragSource)}))]}
  ;; render body
  (connect-drag-source
   (hx/f [:div {:style {:top top
                        :left left
                        :position "absolute"
                        :border "1px solid #333"}}
          text])))

The defnc macro could define two vars in the call site: DraggableBox which is the wrapped component, and DraggableBox_Render which is the non-wrapped component as written in the body of the defnc macro.

With the Hooks proposal gaining such momentum and mindshare, this might eventually be an unneeded enhancement. In the meantime, many React libraries are implemented as a collection of HoCs, so it might be smart to introduce this and then deprecate it once Hooks has been released in a stable version of React.

pepe commented 5 years ago

Just for the history record, react-spring removed all the references to HoC style and went hooks only on the home page. I think it is telling.

lilactown commented 5 years ago

Implemented in master