3

I'm trying to get the current cursor position in a TextInput field but I'm not getting an accurate position depending on what I'm using to input text into the field. onSelectionChange does not appear to be a solution with what I'm trying to solve.

If I use a keyboard on the simulator then it accurately updates the selectChange, but if I move the cursor without changing the text then it does not give me an accurate position of the cursor.

To demonstrate this I have provided the following code. To run it, you must have React Debugger or some way to view console.log output, and you may need to setup a new project for it.

To setup a new project: react-native init TestTextInput --template typescript

Replace export default class App extends Component<Props> { ... } in App.tsx with:

export default class App extends Component<Props, {[key: string]: string}> {
  constructor(props: any) {
    super(props);
    this.state = {
      input: '',
    };
    this.addChar = this.addChar.bind(this);
    this.reset = this.reset.bind(this);
  }

  public textInput: TextInput|null = null;
  public currentSelection: { end: number, start: number } = { end: 0, start: 0};

  addChar(input: string) 
  {
    console.log('==== button pushed ====');
    console.log(this.currentSelection);
    var state: any = Object.assign({}, this.state);
    state.input += input;
    this.setState(state);
  }

  reset(input: string) 
  {
    console.log('==== keyboard pressed ====');
    console.log(this.currentSelection);
    var state: any = Object.assign({}, this.state);
    state.input = input;
    this.setState(state);
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={[{borderWidth: 1, borderColor: 'black', fontSize: 25}]}
          value={this.state.input}
          ref={(input) => this.textInput = input}
          onChangeText={(e) => this.reset(e)}
          onSelectionChange={(e) => this.currentSelection = e.nativeEvent.selection }
        ></TextInput>
        <Button title="Input A" onPress={() => this.addChar('a')} />
        <Button title="Input B" onPress={() => this.addChar('b')} />
      </View>
    );
  }
}

Once you have it synced with a debugger, and have it running in the simulator you'll notice that if I use the left right keys on the keyboard, it does not accurately give me the cursor position. If you use the mouse to change the cursor position like you would with your finger on a phone (with magnifying glass), it as well does not give an accurate position of the cursor.

Is there a way to get the current cursor position regardless of onChangeText or onSelectionChange without writing something in swift?

On TextInput class there is a setNativeProperties method which I can set the selection, I'm wondering if there's an ability to get those properties rather than just set them.

Community
  • 1
  • 1
Paul Carlton
  • 2,785
  • 2
  • 24
  • 42

0 Answers0