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: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.
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.
I guess that’s just a React thing that I needed to be aware of.
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.