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?
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);
});
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>
)
}
}
Instead of:
var currentlyFocussedField = TextInputState.currentlyFocusedField();
use:
var currentlyFocussedField = TextInputState.currentlyFocusedInput();
Then you can:
currentlyFocussedField.measure(...)
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