mirror of https://github.com/status-im/reagent.git
1.6 KiB
1.6 KiB
Question
When using Reagent, how do I use React's refs
?
Answer
Credit: this entry is entirely based on Paulus Esterhazy's Reagent Mysteries series
We'll start with a code fragment, because it is worth a 1000 words:
(defn video-ui []
(let [!video (clojure.core/atom nil)] ;; stores the
(fn [{:keys [src]}]
[:div
[:div
[:video {:src src
:style {:width 400}
:ref (fn [el]
(reset! !video el))}]]
[:div
[:button {:on-click (fn []
(when-let [video @!video] ;; not nil?
(if (.-paused video)
(.play video)
(.pause video))))}
"Toogle"]]])))
Notes:
- That's a Form-2 component. That allows us to retain state outside of the renderer
fn
. - We capture state in
!video
. The state we capture is a reference to a video component. !video
is aclojure.core/atom
and not areaagent.core/atom
- On the
:video
component there's a:ref
callback function which establishes the state in!video
- Thereafter,
@!video
is used with the:button's
:on-click
to manipulate thevideo
- For full notes read Paulus' blog post
- For more background on callback refs, see React's documentation
Up: FAQ Index