Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Cursor Position on TextInput React-Native

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

like image 773
DantheMan Avatar asked Jun 21 '15 04:06

DantheMan


2 Answers

onSelectionChange={(event) => console.log(event.nativeEvent.selection)}
like image 173
Maksim Avatar answered Nov 20 '22 08:11

Maksim


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:

enter image description here

like image 5
Esmaeil Avatar answered Nov 20 '22 10:11

Esmaeil