July 8, 2016

Issue w/ default-value using reagent and rendering multiple times

currently i am creating a hybrid mobile app using clojurescript and the amazing reagent library

during development i faced an issue w/ the "default-value" of an "input" tag. the way to reproduce the issue is as follows:

where

  • we have 2 pages "from" and "to" and control cycles between them (they are rendered one after the other in cycles), starting from "from"
  • "to" has a "form" w/ an "input" (type=text) field that has the "default-value" set to "hi there"
  • what i noticed is that the 1st time that "to" was rendered, "hi there" was shown in the "input"
  • but if you
    • change the value in the input (to say "hello world")
    • go to "from" (by clicking "Submit")
    • come again to "to" (by clicking "Click Me")
    • then the value shown for "input" becomes "hello world", instead of the expected "hi there"
    • this was confusing because, i expected "hi there" to be shown since (according to me) "to" was being rendered "freshly" (everytime control moved from "from" to "to")
    • the reason for this is that, as mentioned in the "Default Value -> Note" on react forms docs, the "defaultValue" works only on the initial render. it also says that "If you need to update the value in a subsequent render, you will need to use a controlled component."

so we need to maintain the state for the "input" component as follows

fortunately, react has come up w/ a new version v0.4 which says that the behavior discussed above was a common pattern and has been implemented. and we should hopefully see the same supported in the next version of reagent too!

Tags: web hybrid frontend reagent app render mobile react