This episode is for subscribers only. Sign Up or Log in to watch it.

10. Reagent part 2: Cursors

Published 07 July 16

We continue building a Kanban board with Reagent, adding functionality to edit cards. In the process you’ll learn all about Reagent’s cursors and event handlers.

Show notes

In Episode 9. about Reagent we ended with a mock version of our Kanban board. If you want to follow along from where we left off you can grab the code from Github. Just follow the instructions in the show notes.

All parts of the board are already there, but they don’t do anything yet, it could just as well have been static HTML. To change that we’ll be using Reagent’s cursors. Let’s get started!

Before diving into our app we’ll have to learn how cursors work. Suppose you have a single card stored in a Reagent atom, the card has the :title “Hello Island.”.

(def card-atom (r/atom {:title "Hello Island."}))

Updating it is straightforward, here’s a function that changes the card’s title. We change the atom with swap!, which takes an atom and a function to apply to the value in the atom. Any extra arguments to swap! are passed through as extra arguments to the function, so we can actually simplify this.

Now we can use this function to change the value in the atom, here’s the result.

(defn set-title! [card title]
  (swap! card assoc :title title))

;; same as
(defn set-title! [card title]
  (swap! card (fn [c] (assoc c :title title))))

(set-title! card-atom "Hello Turtles")

card-atom ;;=> #<Atom: {:title "Hello Turtles"}>

browse source code

The starting point of this episode is the branch ep-9-reagent, the end point is ep-10-reagent-cursors. You can follow along by starting with

git clone -b ep-9-reagent


Creating cursors:

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

(r/cursor <atom> <path)

;; example
(def board (r/atom {:columns []}))

(def cols-cursor (r/cursor board [:columns]))

(swap! cols-cursor conj {:title "todos" :cards []})

@board ;;=> {:columns [{:title "todos" :cards []}]}

Reagent cookbook has a cursors recipe