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:

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);
}}
/>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With