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.
In order to get the position of the cursor the only thing you need is onSelectionChange https://reactnative.dev/docs/textinput#onselectionchange. The function will return the start and the end values.
To change the React Native text input cursor color, we can set the selectionColor prop to the cursor color. to set selectionColor to 'green' to set the cursor color on the text input to green.
As @this.lau_ says there is a controlled property called selection
which accepts an object with keys start and end.
Example:
class ControlledSelectionInput extends Component { state = { selection: { start: 0, end: 0 } } // selection is an object: { start:number, end:number } handleSelectionChange = ({ nativeEvent: { selection } }) => this.setState({ selection }) render() { const { selection } = this.state; return <TextInput selection={selection} onSelectionChange={this.handleSelectionChange} /> } }
You can also programmatically set the selection by getting a ref to the component and using setNativeProps
like this:
this.inputRef.setNativeProps({ selection:{ start:1, end:1 } })
Example:
class SetNativePropsSelectionInput extends Component { inputRef = null render() { const { selection } = this.state; return ( <View> <TextInput ref={this.refInput} /> <Button title="Move selection to start" onPress={this.handleMoveSelectionPress} /> </View> } refInput = el => this.inputRef = el handleMoveSelectionPress = () => this.input.setNativeProps({ selection: { start: 0, end: 0 } }) }
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