Search code examples
clojureclojurescriptreagenthiccup

Simple Clojurescript form


I'm working with Reagent and CLJS, familiar with React and Clojure, less so CLJS. I'd like to make a simple form, but it's not obvious to me in CLJS.

(defn form []
  [:div
   [:input {:type "text" :name "first-name" :id "first-name"}]
    [:button  {:on-click (fn [e] (test-func "hello"))}
  "Click me!"]
])

I want to grab the value of that input, and pass it to a function when the button is clicked. How do I get that input's value into my on-click function?


Solution

  • The idiomatic and technically correct way is to avoid keeping any state in DOM and accessing it directly. You shouldn't rely on the input's value. Keep the state as Reagent's atom. Then you can do anything with it.

    (def first-name (r/atom ""))
    
    (defn form []
      [:div
       [:input {:type "text"
                :value @first-name
                :on-change #(reset! first-name (.-value (.-target %)))
                }]
       [:button  {:on-click #(test-func @first-name)} "Click me!"]])