Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use react native TextInput selection props?

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

like image 614
Ryan Pergent Avatar asked Mar 06 '26 10:03

Ryan Pergent


1 Answers

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);
      }}
    />
  );
};
like image 138
ido han Avatar answered Mar 08 '26 00:03

ido han



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!