Fork me on GitHub
#reagent
<
2019-01-15
>
aisamu14:01:16

Hi! Is it possible to get the ref of a reactify-ed component? I'm mocking a JSX component from CLJS and I can't get a pointer to that element's DOM node, getting what seems to be a constructor object instead.

(defn sub [props]
  [:p {:ref #(js/console.log "comp:" %)} "Hello" (:name props)])

(defn hello [name]
  [:div 
    [:p {:ref #(js/console.log "direct:" %)} "Hello" (:name props)]
    [sub {:ref #(js/console.log "parent:" %) :name name}]
    [:> (r/reactify-component sub) {:ref #(js/console.log "react:" %) :name name}]])

;; Console output after rendering [hello "Reagent"]
direct: <p>​…​</p>
comp: <p>​…​</p>
comp: <p>​…​</p>
react: t {props: {…}, context: {…}, refs: {…}, updater: {…}, state: null, …}

juhoteperi14:01:36

@aisamu If the React component doesn't use ref forwarding or provide separate dom element ref property, no. https://reactjs.org/docs/forwarding-refs.html

aisamu14:01:11

Got it, thanks! Would this still apply if reagent is generating the React component from plain hiccup? (with reactify-component, as in the example)

juhoteperi14:01:24

Hmh, I'm not completely sure what is happening here, but: 1. ref printing "parent: " is not used because sub component doesn't use ref from props anywhere 2. :> and reactify-component together might generate additional adapter class which might explain why both refs are called

aisamu14:01:11

Got it, thanks! Would this still apply if reagent is generating the React component from plain hiccup? (with reactify-component, as in the example)

juhoteperi14:01:29

If you want to create "JSX" or native React component, it might be better to just create real React function directly instead using reactify-component.

(defn sub [props]
  (react/createElement "p" #js {:ref #(js/console.log "comp:" %)} "Hello" (.-name props)))

👌 5
juhoteperi14:01:40

And I guess you could try forwardRef also:

(def sub (react/forwardRef (fn [props ref] (react/createElement "p" #js {:ref ref} "Hello" (.-name props)))))

aisamu15:01:17

Interesting, thanks a lot!