Skip to content

Instantly share code, notes, and snippets.

@jmlsf
Last active March 16, 2018 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmlsf/a3c23d2136c32c4792bb512f61661b59 to your computer and use it in GitHub Desktop.
Save jmlsf/a3c23d2136c32c4792bb512f61661b59 to your computer and use it in GitHub Desktop.
Input elements in reagent (and react)
The basic "cursor jumping" issue: facebook/react#955
I.E. onchange events out of order: facebook/react#7027
The relevant fix in reagent: reagent-project/reagent#253

One problem is that you must update the dom value synchronously.
If you fail to do that, you'll get dropped characters, because eventually you'll get two events in a row and the second one will be based on a stale value (so the first event will get overwritten).

In contrast, no matter how long you take in the onchange handler, the browser does the right thing.

Consider this:

(defn test-component []
  (let [*value (reagent/atom "")]
    (fn []
      [:input {:value     @*value
               :on-change (fn [e]
                            (loop [n 0 t 1]
                              (if (= n 1000000)
                                t
                                (recur (inc n) (* t n))))
                            (reset! *value (-> e .-target .-value)))}])))

Although the input will lag horribly, it will be correct, no matter how much you type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment