Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the prop nativeID to locate a View in native code

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.

like image 398
Salma Ali Avatar asked Sep 24 '18 16:09

Salma Ali


People also ask

What is Nativeid?

Native ID is a unified login that gives you access to both your Native Instruments account and Sounds.com.

How does react native work?

React Native works by spinning up a Javascript thread that interprets Javascript code, communicating with native components under the hood. For example: This is Javascript code that is interpreted and converted into an Android TextView.


1 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.

like image 188
Ram Raut Avatar answered Oct 22 '22 21:10

Ram Raut