Skip to content

Instantly share code, notes, and snippets.

@danielytics
Last active March 7, 2018 16:24
Show Gist options
  • Save danielytics/d4374cd51deec7201250 to your computer and use it in GitHub Desktop.
Save danielytics/d4374cd51deec7201250 to your computer and use it in GitHub Desktop.
Wrap React components for access in Reagent
;; Eclipse Public License 1.0 http://opensource.org/licenses/eclipse-1.0.php
(defn make-wrapped-component
"Wrap a React component in such a way that the raw JS component is accessible.
Useful for for calling methods on the native React component."
[component]
(fn [attrs & children]
(r/create-class
{:component-did-mount
(fn [this]
(when-let [component-ref (:ref attrs)]
(reset! component-ref (aget this "refs" "_this"))))
:reagent-render
(fn [attrs & children]
(apply
r/create-element
component
(-> attrs
(dissoc :ref)
(assoc :ref "_this")
(clojure.set/rename-keys {:class :className})
reagent.impl.component/camelify-map-keys ; maybe best not to use reagent.impl.* functions...
reagent.impl.component/map-to-js)
children))})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Usage:
(def my-wrapped-component (make-wrapped-component js/react-component))
(defn my-component []
(let [my-atom (atom nil)]
(fn []
[:div
[my-wrapped-component {:ref my-atom}]
[:div {:on-click #(.callFunction @my-atom)} "Click me to call callFunction"]])))
;; NOTE: callFunction would need an extern for advanced compilation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment