Fork me on GitHub
#reagent
<
2019-06-21
>
Nolan00:06:44

@lilactown i have a div which i render with a ref. in component-did-mount, i want to get the height and width of the div using the ref and use those values to set the dimensions of a canvas which is nested within the div. problem is, the height and width of the div in component-did-mount are initially slightly off. if i instead, wait ~100ms, and then get the dimensions of the div, everything will be correct.

Nolan00:06:21

here's a code excerpt, if you'd like to take a look:

([attributes props]
   (let [node    (atom nil)
         sketch  (atom nil)
         handler (atom nil)]
     (r/create-class
      {:component-did-mount
       (fn []
         (println "drawing mounted")
         (let [s (-> props (assoc :node @node) ->sketch)]
           (reset! sketch s)
           (when-let [on-resize (:on-resize props)]
             (let [rh (->resize-handler @node on-resize s)]
               (.addEventListener js/window "resize" rh)
               (reset! handler rh))))
         #_(js/setTimeout
            #(let [s (-> props (assoc :node @node) ->sketch)]
               (reset! sketch s)
               (when-let [on-resize (:on-resize props)]
                 (let [rh (->resize-handler @node on-resize s)]
                   (.addEventListener js/window "resize" rh)
                   (reset! handler rh))))
            100))
       :reagent-render
       (fn [] [:div (assoc attributes :ref (partial reset! node))])})))

Nolan00:06:24

fyi, the canvas gets inserted into the dom by the call to ->sketch