Fork me on GitHub
#reagent
<
2018-09-24
>
patrick18:09:41

Hi guys, I'm a beginner with clojure and reagent and have a (probably) stupid question. I started playing around with components. I encountered an issue when trying to map a list of values to components like

(defn counter-component [initial-value]
  (let [counter (r/atom initial-value)]
    (fn []
      [:div
       [:button {:on-click #(swap! counter inc)} @counter]])))

(defn page[]
  [:div (map #([(counter-component %) {:key %}]) (range 0 10))])
I would expect this to render 10 buttons which increase their values as soon as I press them. Instead i get an error saying Invalid arity 0... I do not get where the issue is coming from. Can somebody of you guys maybe help me out? (Note: I read through a lot of tutorials already, but did not find the answer I seek, as most of them do not use the component to render a list of items or I'm just blind already ^^)

justinlee18:09:26

@patri.pichler you are trying to invoke a vector

gadfly36118:09:32

@patri.pichler try this

(defn page []
  [:div
   (for [x (range 0 10)]
     ^{:key x}
     [counter-component x])
   ])

patrick18:09:02

Thank you that worked!

gadfly36118:09:21

This is from the reagent site

Note: The ^{:key item} part above isn’t really necessary in this simple example, but attaching a unique key to every item in a dynamically generated list of components is good practice, and helps React to improve performance for large lists. The key can be given either (as in this example) as meta-data, or as a :key item in the first argument to a component (if it is a map). See React’s documentation for more info.
I mention that because in your page example, you were trying to add a :key in the attribute hashmap ... which should work too ... but the problem was the #([ part when you were mapping over the range

patrick18:09:15

Thank you very much!

patrick19:09:16

Would it be possible though to use a map instead of the for comprehension?

gadfly36119:09:57

(defn page[]
  [:div
   (map #(vector (counter-component %) {:key %})
        (range 0 10))
   ])

gadfly36119:09:54

As an aside, the for version is more common 'in the wild' (because of things like using :let inside of the for, etc.) but you can use map like the above if you wanted

patrick19:09:06

Thank you very much! You've helped me a lot! I somehow read over that part with the ^{ from the reagent site.

gadfly36119:09:23

No worries, it's definitely easy to miss

👍 4
Diego21:09:16

Sorry for the repost: Has anybody used accountant with secretary (in a regent app)? I want to implement navigation and page “scrolls” for links like /some-page#my-anchor. How can I solve this? The accountant docs are not clear about this point/