How, in a shadow-grove component, to access the DOM element?

Given a very simply shadow-grove component, such as:

(defc thing []
  (render (<< [:div "hello"])))

And supposing, just for example, that I wanted to log the inner HTML of the component after every render, the component may be modified like this:

(defc thing []
  (hook
    (sg/render-effect
      (fn [env]
        ;; Somehow bind the element as `el`, in order to log to the console:
        (js/console.log (.-innerHTML el)))))
  (render (<< [:div "hello"])))

How would I get that element which the comment indicates?

Same logic as in React. You use a ref.

(defc thing []
  (bind el-ref (sg/ref))
  (hook
    (sg/render-effect
      (fn [env]
        ;; Somehow bind the element as `el`, in order to log to the console:
        (js/console.log (.-innerHTML @el-ref)))))
  (render (<< [:div {:dom/ref el-ref} "hello"])))
1 Like

Funny, I was just thinking this moment of updating my question to mention, “in Reagent I just use a ref…,” and here we go. Thanks!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.