Fork me on GitHub
#reagent
<
2023-02-25
>
jlfischer06:02:13

I’m having a little trouble with the subtleties involved in tying an input’s value to a Reagent atom. I have a simple text input component like this:

(defn text-input
  [initial-val]
  (let [value (reagent/atom (or initial-val ""))
        change-fn (fn [e]
                    (reset! value (-> e .-target .-value)))]
    (fn text-input-render [initial-val]
      [:input {:type     "text"
               :value    @value
               :on-input change-fn}])))
I can enter text in that input box without trouble, but if I otherwise edit it, like deleting some characters from earlier in the string, my cursor keeps jumping to the end of the string, like this:

jlfischer06:02:24

It makes sense: the input event fires, I update the atom, the component re-renders with the new value, but I’ve seen that re-com’s text input components don’t do that, and I’d like to understand why.

jlfischer06:02:45

Oh bother; :on-input gives me the behavior I’m seeing, but :on-change does the right thing. I was under the impression that :on-change doesn’t necessarily fire for every change to the input value, so I defaulted on :on-input.

jlfischer06:02:00

I guess that’s just a React thing that I needed to be aware of.

kennytilton13:03:28

Yeah, sorry I did not see your message until now. React definitely changed the semantics of :on-change. ISTR it had something to do with wanting the state in the app to match the state in the DOM, so once the user added/removed a letter they do not wait for enter or focus loss as is the standard. Kind of a scary deviation. Another thing: in the JS console poking around, if you put a handler on a widget, you won't find it on the associated DOM. React puts them all on the window, I suppose because they are doing clever things with DOM/VDOM/efficiency.