Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Preloader example in Reagent
(ns preloader
"Example from"
(:require [reagent.core :as r]))
(def status (r/atom {:progress 0
:length 0
:dasharray 0
:dashoffset 0}))
(defn set-progress [status]
(let [progress (:progress @status)
rnd (* (js/Math.random) 0.1)
;new-progress (js/Math.min (+ progress rnd) 1) ;; go from 0..1
new-progress (+ progress rnd)]
(swap! status assoc :progress new-progress)))
(defn interval [interval-ref]
(js/setInterval #(set-progress status) 80))
(defn progress-draw [status]
(* (:length @status) (- 1 (:progress @status))))
(defn preloader []
(fn [this]
(let [el (.getElementById js/document "loader__circle")
total-length (.getTotalLength el)]
(swap! status assoc
:length total-length
:dasharray total-length
:dashoffset total-length)))
(fn [this]
(swap! status assoc :dashoffset (progress-draw status)))
(fn []
[:svg {:class "inner"
:width 60
:height 60
:viewBox "0 0 80 80"}
[:path.loader__circlebg {:d "M40,10C57.351,10,71,23.649,71,40.5S57.351,71,40.5,71 S10,57.351,10,40.5S23.649,10,40.5,10z"}]
[:path#loader__circle.loader__circle {:d "M40,10C57.351,10,71,23.649,71,40.5S57.351,71,40.5,71 S10,57.351,10,40.5S23.649,10,40.5,10z"
:style {:stroke-dasharray (:dasharray @status)
:stroke-dashoffset (:dashoffset @status)}}]]])}))
;; how to use
(defn parent-comp []
(let [interval-ref (r/atom nil)]
(reset! interval-ref (interval interval-ref))
(fn []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment