Say that you have a text field which is the input of a chat program written in cljs with reagent. It could look something like this:
(defn chat-input []
(let [written-text (atom "")]
(fn []
[:textarea
{:value @written-text
:on-change #(reset! written-text (-> % .-target .-value))}])))
Now the easy way to implement sending a message is to add a send button. But there's one interaction that's so integral to chat that you can't really be without it: That enter or shift-enter sends the message. But I can't figure out how to implement it.
My first try was to simply add a :on-key-press event handler to send the message and reset the state to "". This solution was inspired by How to detect enter key press in reagent.
(defn chat-input []
(let [written-text (atom "")]
(fn []
[:textarea
{:value @written-text
:on-change #(reset! written-text (-> % .-target .-value))
:on-key-press (fn [e]
(let [enter 13]
(println "Key press" (.-charCode e))
(if (= (.-charCode e) enter)
(reset! written-text "")
(println "Not enter."))))}])))
The problem being that the call to (reset! written-text "")
in :on-key-press
has no effect, probably because it's overridden by the :on-change
event handler.
So do you have any ideas on how to implement this functionality? If so, please do share!