Sergei-Udris
Sergei-Udris

Reputation: 121

how to rerender reagent ui with react 18 and shadow-cljs reload?

how to rerender the whole reagent tree when we save file and shadow-cljs reloads?

Upvotes: 7

Views: 2481

Answers (2)

n2o
n2o

Reputation: 6487

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}}}}}

Upvotes: 19

Sergei-Udris
Sergei-Udris

Reputation: 121

https://github.com/move-me-to-ipfs-shipyard/Fennec/blob/bbfb566211041dd57b419ffd95f642026bb989a8/src/Fennec/ui.cljs#L263

(: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])))))

Upvotes: -2

Related Questions