Search code examples
clojurelist-comprehensionreagenthiccup

Clojure list comprehension and unique values for reagent


Let's assume that we have this grid with values that can be 0 or 1:

(def grid [[1 0 1]
           [1 0 0]
           [1 0 1]])

Now I want to transform grid into an html Hiccup like format using list comprehension:

(defn cell-component [is-it-1 key]
  ^{:key key} [:td (if (= is-it-1 1) {:class "is-it-1"})])


(defn grid-html []
  ([:table
   [:tbody
   (for [row grid]
      ^{:key row} [:tr 
                      (for [cell row]
                      (cell-component cell how-i-can-generate-a-index?))])]]))

The table is generated correctly but I don't have any ideas to how to make a unique index for my td. what how-i-can-generate-a-index? should be?


Solution

  • In your case, each cell is uniquely identified by its index within the row. Also, it would be more natural to specify the children's keys in the parent structure rather than in the components:

    (defn cell-component [is-it-1]
      [:td (if (= is-it-1 1) {:class "is-it-1"})])
    
    (for [[i cell] (map-indexed vector row)]
      ^{:key i} [cell-component cell])
    

    Note that you should similarly assign index-based keys to rows - ^{:key row} won't work if you have duplicating rows in your table.