clojureclojurescriptreagenthiccup

How to get index for an item in reagent


When I iterate over vector in Reagent, like this:

(for [item ["rattata" "pidgey" "spearow"]]
  [:li item])])

I would like to get index of a specific item - like this:

  [:li item index]

I'm not asking about general clojure 'for', because another way to iterate over vector will satisfy me as well.


Solution

  • This is actually a general Clojure question, rather than specific to Reagent, but there are a few way you could do this.

    You can approach it similarly to your current code with something like

    (def items ["rattata" "pidgey" "spearow"])
    (for [index (range (count items))]
      [:li (get items index) index])
    

    You could also use map-indexed

    (doall (map-indexed (fn [index item] [:li index item]) items))
    

    The doall in this case is for Reagent, as map and friends return lazy lists that can interfere with Reagent (it will print a warning to the console if you forget it).