Fork me on GitHub
Jakub Holý (HolyJak)00:07:24

@tony.kay I have written about how to use forwardRef with Fulcro and would very much appreciate your feedback, especially with the regard of the necessary conversion from #js props to a clj map. Perhaps there is a simpler way that I am missing? I would then also like to create a PR to add this to a suitable place of the F. Dev. Guide, likely in the Hooks chapter as it took some effort to figure this out.


I’m not sure how this is working:

(defsc ChildWithRef [_ {:keys [forwarded-ref label] :as props}] ; (1)
  (dom/button {:onClick #(some-> forwarded-ref .-current .focus)}

(def ui-child-with-ref (comp/factory ChildWithRef))

(def child-with-ref
  (react/forwardRef                         ; (2)
    (fn [js-props ref]
      (ui-child-with-ref                    ; (3)
        (-> js-props
            (js->clj :keywordize-keys true) ; (4)
            (assoc :forwarded-ref ref))))))

(defsc Root [_ _]
  {:use-hooks? true}
  (let [^:js ref (hooks/use-ref nil)]
      (dom/input {:ref ref, :value "" :type "text"})
      ((interop/react-factory child-with-ref) ; (5)
        {:ref ref :label "Focus, v3!"}))))    ; (6)
because you’re using defsc, and then you’re messing with the low-level js props…but Fulcro’s props are actually in the js props at fulcro$value (I think…or is it state). Anyway, when you destructure forwarded-ref you’re pulling from that and NOT the low-level js props.


did you test this?


OH….I see…you’re calling the factory after messing with the props


yeah, it’s a little messy, but I see

Jakub Holý (HolyJak)16:07:23

Yes I tested it but feel there must be better way. I also realized later it does not cover the full use case, where my Fulcro component will be passed to a non-fulcro component and thus I likely need with-parent-context .


If you want to pass a Fulcro component AS the HOC, then I’d write a low-level function and make a factory for it (i.e. make a js hooks component), and do the “adapting” in that function. Then React is none the wiser. The new hooks use-component stuff makes that much easier to use when doing composition.

Jakub Holý (HolyJak)06:07:27

@tony.kay thanks a lot for that tip. I have applied it here and it works perfectly. Anything you would change there?

Jakub Holý (HolyJak)22:07:02

A simplified example of using forwardRef while passing the component to a HoC JS component (thus needed with-parent-context), leveraging hooks/with-component here:


I don’t have anything else right now. Sorry, don’t have time to look as carefully as I’d like

🙏 1