eav db
eav db

Reputation: 595

Purpose of : "^{:key item}"

I'm reading http://reagent-project.github.io/

A snippet of code there is:

(defn lister [items]
  [:ul
   (for [item items]
     ^{:key item} [:li "Item " item])])

What is the meaning of the ^{:key item} and why do we want it? [The documentation refers to making Reflect faster.]

Upvotes: 4

Views: 272

Answers (1)

Svante
Svante

Reputation: 51501

React needs to identify the individual list items, so that it can tell which ones have changed. Otherwise, React can only throw away the entire list when rerendering. Therefore, you need to add a key.

In React (JSX):

<li key={item.whatever}>
  {item.bar}
</li>

In reagent, you add the key as metadata to the Hiccup form. Reagent takes care of setting the key for React then.

^{:key (.-whatever item)} [:li (.-bar item)]

You can use anything uniquely identifying the content of the list element. In ClojureScript/Reagent, you usually use the item itself.

Upvotes: 6

Related Questions