user31415926 user31415926 - 1 month ago 21
React JSX Question

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.]

Answer

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.