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 workingAh that makes sense. Thanks @lilactown and @noisesmith
Ah nice I always just passed it into the props
Any reason to prefer setting the meta data instead?
Not for html elements like :li. If you’re using a component you’ve defined, then you might not have a place to set those props. E.g. [some-component foo bar] In this case there’s no props map to pass a key to, so you’ll want to use metadata
ah right makes sense thanks
It seems like this is Reagent metadata?
It’s syntax for adding metadata to the vector being constructed
Reagent checks a few places for keys when converting a vector into a React element
One is props , so you could just pass in the key like any other prop
Another is metadata on the vector
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
^:foo
is often seen, it translates to ^{:foo true}
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}
yeah I feel some of the docs are just outdated, thing is, when learning, it is hard to determine which thing is wrong