Fork me on GitHub
#fulcro
<
2022-04-29
>
Jakub Holý (HolyJak)14:04:48

@tony.kay do you have any tips for using React.forwardRef with Fulcro / hook-based components? I am trying to translate this example https://bitworking.github.io/react-gsap/src-components-timeline#advanced-multiple-targets to Fulcro, where I suppose TargetWithNames should be a hook-based component (since it uses useRef ). A complication is that it is then passed to a library function like this <Timeline target={<TargetWithNames />}> so I also need comp/with-parent-context . I have now

(defsc TargetWithNames [_ _] (let [div1 (react/useRef) ..] ...)
;(def ui-target-with-ref (comp/factory TargetWithNames)) ; => warning about ref x fn components
(def ui-target-with-ref (comp/factory (react/forwardRef TargetWithNames))) ; => warn about missing ref argument
;; somewhere else:
(dom/timeline {:target (comp/with-parent-context this
                             (ui-target-with-ref {}))} ...)
which does not throw any errors but also does not render what I expect. Without wrapping with forwardRef I get the warning > Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? but with it, it complaints it expected two args (props, ref) but did not get them. I also suspect that with-parent-context will not work with a wrapped function that is not directly a Fulcro component.

tony.kay15:04:10

I don’t know that the existing wrappers will work with forwardRef, since you have to work at the low-level js props layer for that. The fulcro factories expect clj props which they then piggyback onto the js props, and of course the macro does the opposite: extracts fulcro props from the js props for you. So, since forwardRef is expecting a function of js-props and ref, give it one (manually). When that function is called, do what the factory of Fulcro does with raw js props.

👀 1
tony.kay15:04:17

actually, you’ll have to probably also look at what the macro-generated code does with props, since that is where the unwrapping is

tony.kay15:04:34

If I get some free time today I’ll give you an example

tony.kay18:04:24

Here are two demos of passing along nested refs. Of course if the custom leaf component needs a query and such you’d want to use computed props for the forwarded ref. https://github.com/fulcrologic/fulcro/blob/develop/src/workspaces/com/fulcrologic/fulcro/cards/ref_cards.cljs

😻 1
Jakub Holý (HolyJak)18:04:27

Thanks a lot! So this is an example of passing a ref via the custom property :forward-ref , right? I guess that should work, I just have to find out whether it plugs nicely into the library we use (that takes a :target prop = an element/component)

tony.kay23:04:47

If you need to go the other way you will have to do a little coding

👍 1