Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the position of the currently focussed input?

Tags:

react-native

I need to know the position of the currently focussed input to make some calculations. At the end I want to call .measure() on it.

What I got:

import { TextInput } from 'react-native';

const { State: TextInputState } = TextInput;
var currentlyFocussedField      = TextInputState.currentlyFocusedField();

console.log('currentlyFocussedField', currentlyFocussedField);

But this only returns the id of the text field (like 394, and the next field is 395). How can I access the real element/object or how do I get its position on the screen?

like image 272
Thomas Kekeisen Avatar asked Aug 24 '16 15:08

Thomas Kekeisen


3 Answers

I don't know how you can access the React component from the numeric reactTag in javascript, but you can use the same UIManager.measure(reactTag, callback) function that RN uses internally to make .measure() work.

It's not documented, but you can find the source here, for iOS, and here for Android.

You can use this to get the all the size values of the native view. For example, drawing from your example above:

import { UIManager, TextInput } from 'react-native';

const { State: TextInputState } = TextInput;
const currentlyFocusedField = TextInputState.currentlyFocusedField();

UIManager.measure(currentlyFocusedField, (originX, originY, width, height, pageX, pageY) => {
  console.log(originX, originY, width, height, pageX, pageY);
});
like image 67
Michael Helvey Avatar answered Jan 04 '23 17:01

Michael Helvey


This is how I'm getting the position of a focused input to scroll to it:

import { findNodeHandle, ScrollView, TextInput, UIManager } from 'react-native'

class SomeForm extends Component {
  scrollTo (element) {
    const handle = findNodeHandle(this[element])
    if (handle) {
      UIManager.measure(handle, (x, y) => {
        this._scrollView.scrollTo({
          animated: true,
          y
        })
      })
    }
  }

  render () {
    return (
      <ScrollView
        ref={(element) => {
          this._scrollView = element
        }}
      >
        <TextInput
          onFocus={() => this.scrollTo('_inputName')}
          ref={(element) => {
            this._inputName = element
          }}
        />
      </ScrollView>
    )
  }
}
like image 27
Luciano Ropero Avatar answered Jan 04 '23 17:01

Luciano Ropero


Instead of:

var currentlyFocussedField = TextInputState.currentlyFocusedField();

use:

var currentlyFocussedField = TextInputState.currentlyFocusedInput();

Then you can:

currentlyFocussedField.measure(...)

like image 38
cchapin Avatar answered Jan 04 '23 15:01

cchapin