Josh
Josh

Reputation: 2587

How can I pass data to a native iOS view from react native?

I've read the react-native docs online but I'm still struggling to understand. How can I instantiate a native view with some data that I've fetched on the JS side of things? Basically I want to pass some JSON over a bridge, translate that JSON into an NSDictionary, and then instantiate a view with that NSDictionary. I've been able to successfully create a native view, but I'm struggling with how to pass any data to it. Do I need to look at RCT_EXPORT_VIEW_PROPERTY? Or RCT_EXPORT_CUSTOM_VIEW_PROPERTY?

On the JS side, I have made my native component ready for use like this:

import { requireNativeComponent } from 'react-native';
module.exports = requireNativeComponent('MyNativeView', null);

Then, in my app.js file, I simply import the view:

import MyNativeView from './MyNativeView'; 

and render it like so:

render() {
return (
    <MyNativeView />
);
}

This all works wonderfully. The bridge is working fine, I've left that code out for the sake of brevity. What I need to do is pass some data to 'MyNativeView'. Something like

`<MyNativeView data={this.JSONData} />`

How do I do that?

Upvotes: 3

Views: 2062

Answers (1)

Amloelxer
Amloelxer

Reputation: 772

I know it has been awhile, but I believe this is the answer for future internet lurkers.

Once you have declared the "data" prop in Javascript, there are two things you need to do in Objective-C / Swift land.

The first thing is in your .m class where you export the native iOS View, you need something like this:

RCT_EXPORT_VIEW_PROPERTY(data, NSDictionary *)

This will then automatically call the setter function of "setYourCustomerPropertyName" on whatever view you are returning in your view manager class. However, if you don't create the native iOS view with this setter function and you pass a prop through in javascript land, you'll get the classic "unknown instance sent to selector crash".

To avoid that and to actually get access to your data, all you have to do is make that setter on the view, and then you'll be able to access that data crash free.

In Swift

class MyCustomView: UIView {
   func setData(data: Dictionary<String,Any>) {
     // Access your data here 
   }
}

In Objective-C

#import "MyCustomView.h"

@implementation MyCustomView

-(void)setData:(NSDictionary *)data {
  // set data here
}

@end

Then all together

@interface MyNativeViewManager()

@end

@implementation MyNativeViewManager

RCT_EXPORT_MODULE(MyNativeView)
RCT_EXPORT_VIEW_PROPERTY(data, NSDictionary *)

- (UIView *)view {
  return [MyCustomView new];
}

Upvotes: 3

Related Questions