Is it possible to add the prop nativeID
to a view like follows:
<View nativeID="viewId">...</View>
And then use that id to locate the view in my native android and iOS code so I could apply some native method on it. If it is then an example would be appreciated.

- 201
- 2
- 5
3 Answers
Yes it's possible. There is two situations here, if you are using NativeModules or Native Component.
Case 1: NativeModules. I presume in this case, you want to locate view in native side after a button click in JS side. I also presume you know how to create NativeModules in react-native. Ok, at first we need to find the rootview where our view is binded and find that view using helper classes provided by React Native.
Code:
@ReactMethod
public void locateView(String nativeViewId)
{
Activity activity = context.getCurrentActivity();
activity.runOnUiThread(new Runnable() {
@Override
public void run()
{
View rootView = activity.getWindow().getDecorView().getRootView();
View requiredView = ReactFindViewUtil.findView(rootView, nativeViewId);
/** requiredView is your JSX view with nativeID found on Java Side, now you can apply your preferred native functions to it. **/
}
});
}
If you are using NativeComponent then you can easily find the rootView using following code:
Code:
View rootView = getRootView();
And the remaining code is same as using NativeModules. Hope this helps you, if you have any questions feel free to ask me.

- 71
- 5
-
Thanks, Ram. Can a NativeId be assigned to individual elements as well? If unique NativeIds are set to different textInputs and I have the list of nativeIds available to my native module, can I access the element details via function? I am interested in knowing the x,y,height and width of an element at runtime. – mvinayakam Aug 01 '20 at 16:56
-
@mvinayakam you surely can, to know the x,y, height and width of any View at runtime we even don't have to assign nativeID and find that view in native code. React Native provides View prop called onLayout which gets fired every time View with onLayout props gets mounted on the native view hierarchy. You can use onLayout props to find the x,y, height and width of any View. – Ram Raut Oct 25 '20 at 13:19
You can use this after add nativeId to a View:
ReactFindViewUtil.addViewListener(onViewFoundListener);
private ReactFindViewUtil.OnViewFoundListener createOnViewFoundListener() {
return new ReactFindViewUtil.OnViewFoundListener() {
@Override
public String getNativeId() {
return "NativeID";
}
@Override
public void onViewFound(final View view) {
// some code
}
};
}

- 386
- 1
- 6
Yes, it's possible. Suppose you have a view in js,
<CustomView> <View nativeID={'childView'}> <CustomView>
On your android native module call ReactFindViewUtil.findView()
with the view container and native id
ReactFindViewUtil.findView(CustomView, "childView")
The ReactFindViewUtil.findView()
is found in com.facebook.react.uimanager.util
I believe there is similar util on iOS as well. I have not explored it.

- 1