Fork me on GitHub
#reagent
<
2020-08-05
>
John Oerter03:08:00

The reagent docs have this code example:

(defn lister [items]
  [:ul
   (for [item items]
     ^{:key item} [:li "Item " item])])
Can anyone explain the ^{:key item} part to me? I know that it is adding the key attribute for a list in React, but I don't quite understand the Clojure/Reagent syntax part of how this is working

John Oerter03:08:26

It seems like this is Reagent metadata?

lilactown03:08:51

It’s syntax for adding metadata to the vector being constructed

lilactown03:08:15

Reagent checks a few places for keys when converting a vector into a React element

lilactown03:08:36

One is props , so you could just pass in the key like any other prop

lilactown03:08:45

Another is metadata on the vector

noisesmith03:08:49

to be clear, ^{:foo bar} is vanilla clojure, and puts a metadata map onto a collection or symbol, but reagent has a special interpretation of specific metadata keys

3
noisesmith03:08:45

^:foo is often seen, it translates to ^{:foo true}

noisesmith03:08:43

you can combine them

ins)cljs.user=> (def m ^:foo ^{:bar false} {})
#'cljs.user/m
(ins)cljs.user=> m
{}
(ins)cljs.user=> (meta m)
{:bar false, :foo true}

John Oerter13:08:50

Ah that makes sense. Thanks @U4YGF4NGM and @U051SS2EU