Search code examples
clojureclojurescriptreagent

on-click handler for a list item reagent clojurescript


I want to add a on-click handler for each item in my list.

(defonce selected-department (atom "department!"))

(defn sidebar []
  [:div#sidebar-wrapper
   [:ul.sidebar-nav
    [:li.sidebar-brand [:a {:href "#"} "Departments"]]

    ;;[:li [:a {:on-click (reset! selected-department "test!")} "Dairy"]]

    [:li [:a {:href "#"} "Dairy"]]
    [:li [:a {:href "#"} "Deli"]]
    [:li [:a {:href "#"} "Grocery"]]]])

Then selected-department is a label which I want to show/use the data

(defn response-box []
  [:div#form_comparison
   [:label#dlabel @selected-department]])

The commented out piece of code doesn't work. Is there a way to make this work?


Solution

  • Your example is not working because you have to pass a function to :on-click like this :

    [:li [:a {:on-click #(reset! selected-department "test!")} "Dairy"]]
    

    So the only thing that you need to change is to add # before the (reset! ...

    It is the equivalent for

     [:li [:a {:on-click (fn [_] (reset! selected-department "test!"))} "Dairy"]]
    

    Edit :

    This is the full code that I tested and works fine for me :

    (defonce selected-department (atom "department!"))
    
    (defn sidebar []
      [:div#sidebar-wrapper
       [:ul.sidebar-nav
        [:li.sidebar-brand [:a {:href "#"} "Departments"]]
        [:li [:a {:on-click #(reset! selected-department "Dairy") :href "#"} "Dairy"]]
        [:li [:a {:on-click #(reset! selected-department "Deli") :href "#"} "Deli"]]
        [:li [:a {:on-click #(reset! selected-department "Grocery") :href "#"} "Grocery"]]]
     [:label @selected-department]])
    
    (reagent/render-component [sidebar] (.getElementById js/document "app"))
    

    The label at the bottom is updated when an item in the list is clicked.