4

I have the following simple component:

function TestComp() {
    const [selection, setselection] = React.useState({ start: 0, end: 0 });

    return (
        <View style={{ justifyContent: "center", flex: 1 }}>
            <TextInput
                selection={selection}
                onSelectionChange={(event) => {
                    const {nativeEvent: { selection: { start, end } }} = event;
                    setselection({ start, end });
                }}
                multiline={true}
            />
        </View>
    );
}

My problem is that there is often a delay with the update of the value of selection through setselection, which causes the caret to jump around or trigger the error: setSpan(1 ... 1) ends beyond length 0 (Which I believe means that the selection is set to be bigger than the TextInput value)

How am I supposed to use the selection prop? My goal is to be able to move the cursor around when I need.

I am using expo, but with remote debugging off to not cause additional lag.

Jumping example:

enter image description here

Ryan Pergent
  • 4,432
  • 3
  • 36
  • 78
  • I've got something very similar. Have a look at this: https://github.com/facebook/react-native/issues/29063. particularly: https://github.com/facebook/react-native/issues/29063#issuecomment-660375120 looks like an RN0.63.2 target. – Justin Lane Sep 23 '20 at 05:20

1 Answers1

0

I think this might be helpful for you.

const Test = () => {
  const [style, setStyle] = useState({
    TestComponent: {
      backgroundColor: "white",
      height: 40,
      borderWidth: 1,
    },
  });
  const [selection, setSelection] = useState({
    start: 0,
    end: 0,
  });
  const [txt, setTxt] = useState("");
  return (
    <TextInput
      style={style.TestComponent}
      selection={selection}
      value={txt}
      multiline={true}
      onChangeText={(changedTxt) => {
        setTxt(changedTxt);
        console.log("onChangeText", selection);
      }}
      onSelectionChange={(syntheticEvent) => {
        const { nativeEvent } = syntheticEvent;
        const { selection } = nativeEvent;
        console.log("onSelectionChange", selection);
        setSelection(selection);
      }}
    />
  );
};
ido han
  • 13
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 28 '22 at 15:53