Does anyone have any ideas on how to get the caret position of a TextInput
? I tried onSelectionChange
and creating an event emitter from DocumentSelectionState
but neither appear to be working (they don't fire anything, no matter what I select).
For Example: https://rnplay.org/apps/eZnvIA
onSelectionChange={(event) => console.log(event.nativeEvent.selection)}
In react-native <=v0.56 following code get the selection as an object of {state: number, end: number}. The text positions start from 0. For example selection like {start: 0, end: 0} can happen and it means your curser is placed before first character of you text and nothing selected. Another selection type happens when start and end is not equal, like {start: 0, end: 10}, this means you select first 10 character of your text.
By the way as following issue if you use react native v0.57.0 or v0.57.1 in the textInput must be add multiline={true} to everything work properly.
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, TextInput} from 'react-native';
type Props = {};
export default class App extends Component<Props> {
constructor(props) {
super(props)
this.state = {
selection: {start: 0, end: 0},
text: 'This is a sample text',
}
}
render() {
return (
<View style={styles.container}>
<Text>{this.state.selection.start}, {this.state.selection.end}</Text>
<TextInput
style={{ width: 300, borderColor: 'gray', borderWidth: 1 }}
onSelectionChange={({ nativeEvent: { selection } }) => {
this.setState({ selection })
}}
onChangeText={(text) => this.setState({ text })}
value={this.state.text}
/>
</View>
);
}
}
The result is:
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