HomeMathEmailBlogGitHub

Cljs Reagent

2023-08-10

Reagent is a library for ClojureScript that allows the creation of React components. I use Reagent for my TicTacToe ClojureScript implementation, and it is very easy to create a reactive UI. Reagent uses its own atom implementation to keep track of state and update components when that state changes.

If I require Reagent

(require '[reagent.core :as r])
(require '[reagent.dom :as rd])

I can define a Reagent atom:

(def click-count (r/atom 0))

And create a component that uses that atom:

(defn counting-component []
  [:div
   [:label @click-count]
   [:input {:type "button" :value "Click me!"
            :on-click #(swap! click-count inc)}]])

And render that component:

(defn ^:export main []
  (rd/render [counting-component] (.getElementById js/document "app")))

(main)

This creates a button that has a counter that updates when the button is pressed.