Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Michael Thurmond Avatar asked Jun 23 '15 17:06

Michael Thurmond


People also ask

What is reagent ClojureScript?

Reagent is a ClojureScript wrapper around React. It gives you a way to easily create React components. Reagent has three main features that make it easy to use: using functions to create React components, using Hiccup to generate HTML, and storing state in Reagent Atoms.

Why Re-frame?

Re-frame gives you a way to capture the intent of UI actions (Events) and turn them into changes in the application state and the world outside of the browser (Effects). Further, it gives you a way to generate HTML based on changes to the application state (Components).


1 Answers

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.

like image 163
Viktor K. Avatar answered Sep 18 '22 17:09

Viktor K.