On-click handler for clojurescript reagent list item

I want to add a handler to every 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 the label I want to show / use data

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

The commented code snippet does not work. Is there any way to make this work?

+4
source share
1 answer

Your example does not work because you need to pass a function: click as follows:

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

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

This is equivalent to

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

Edit:

This is the complete code that I tested and works great 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 you click an item in the list.

+5
source

All Articles