Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fable.React - editing an Input field moves cursor to end of text

I'm working with the Elmish.Bridge flavor of the SAFE stack.

At the top level of the view, I create an input field like this:

Input.input [ Input.Value(model.FieldValue); Input.OnChange(fun e -> dispatch (EditFieldValue(e.Value))) ]

When I edit that field's value by typing in the middle of it, the model is updated as expected, but the cursor also moves to the end of the input's text.

My model is several layers deep and is completely made of serializable types (primitives, strings, collections, records, and unions).

I tried reproducing this in a toy app (where the model is much less complicated), but it works as expected there - the cursor maintains position.

Is there any way to determine why the cursor is moving under these circumstances?

like image 213
Overlord Zurg Avatar asked Dec 03 '19 05:12

Overlord Zurg


2 Answers

Using the DefaultValue instead of Value should fix this.

This works with Fable.React and Fable.Elmish. Using DefaultValue will not initiate an update of the component / DOM in the react lifecyle and you should therefore not get the cursor changes.

From the link below: react uncontrolled components

In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value.

like image 182
onemorecupofcoffee Avatar answered Nov 15 '22 03:11

onemorecupofcoffee


I had a similar issue, and it turned out to be because React was deleting my DOM object and recreating it. (That in turn was caused by the fact that my React element, though identical in both code branches, had different elements as parents in the two different branches.)

If React does not delete/recreate your DOM object, your cursor should behave normally. If you want to figure out what is causing your DOM to be updated/created, adding some printfns inside of a Hooks.useEffectDisposable call. Add one printfn inside the effect, which will tell you when the element is being mounted, and another inside of the IDisposable to tell you when it's being unmounted.

Using an uncontrolled component can work in certain circumstances, but it will prevent your text from updating if something else changes in the model, e.g. after someone hits an "OK" button you can't clear the textbox. It's better to just get your head around the React lifecycle and fix whatever issue is causing React to re-render your DOM.

like image 44
Maximilian Wilson Avatar answered Nov 15 '22 04:11

Maximilian Wilson