In my React Native app, I am trying to set the cursor position of a TextInput
to a particular position (eg. to the 5th character) but am have trouble doing so as the documentation is lacking a little. I suspect it has something to do with the 'setSelection' property of TextInput
but I cannot seem to find out what to do.
Has anyone successfully done so?
Thanks.
As @this.lau_ says there is a controlled property called
selection
which accepts an object with keys start and end.Example:
You can also programmatically set the selection by getting a ref to the component and using
setNativeProps
like this:Example:
It seems like that selection only works when your Text Input is in focus
You can do the following things to make it work
The idea is whenever your TextInput calls the onChangeText call-back put the focus on your TextInput through refs, as your component is responding to onFocus call back we will set the selection on that call back
I don't see any
setSelection
property in the documentation https://facebook.github.io/react-native/docs/textinput.html, nor do I believe this is supported in core.If you're doing this in Android, I suggest you take Tiny's code and build your own native component. https://facebook.github.io/react-native/docs/native-modules-android.html#content
Of course, you could do the same in iOS if you have the skills... https://facebook.github.io/react-native/docs/native-modules-ios.html#content
I just know the native way:
Maybe you can find same method in React Native.
There is now a selection property on
TextInput
which can be used to set the selection or the caret/cursor position.