how to rerender the whole reagent tree when we save file and shadow-cljs reloads?
- react 18 has new createRoot api
- and even before - if nothing changed calling render has no effect
how to rerender the whole reagent tree when we save file and shadow-cljs reloads?
With react v18, you need to create the root node only once. After this, you can call the .render()
function from it to (re-)render your application.
Also, you need to configure a function / behavior to tell shadow-cljs what it should do on during reload.
Here is a full example, taken from here https://github.com/schnaq/cljs-reagent-template
(ns playground
(:require ["react-dom/client" :refer [createRoot]]
[goog.dom :as gdom]
[reagent.core :as r]))
(defn- main []
[:main.container.mx-auto
[:h1 "Welcome to your app"]])
;; -----------------------------------------------------------------------------
(defonce root (createRoot (gdom/getElement "app")))
(defn init
[]
(.render root (r/as-element [main])))
(defn ^:dev/after-load re-render
[]
;; The `:dev/after-load` metadata causes this function to be called
;; after shadow-cljs hot-reloads code.
;; This function is called implicitly by its annotation.
(init))
shadow-cljs is configured to call the init-function from playground/init.
;; shadow-cljs.edn
{...
:builds {:frontend {:modules {:main {:init-fn playground/init}}}}}
(:require
["react-dom/client" :as Pacha.dom.client]
[reagent.core :as Kuzco.core])
; seed.cljs
(defonce root {:dom-rootA (atom (Pacha.dom.client/createRoot
(.getElementById js/document "ui")))})
; ui.cljs
(:require [Fennec.seed :refer [root]])
(defn reload
[]
(when-let [dom-root @(:dom-rootA root)]
(.unmount dom-root)
(let [new-dom-root (Pacha.dom.client/createRoot
(.getElementById js/document "ui"))]
(reset! (:Pacha-dom-rootA root) new-dom-root)
(.render @(:Pacha-dom-rootA root)
(Kuzco.core/as-element [rc-current-page])))))
© 2022 - 2024 — McMap. All rights reserved.