how to pass a react component as a native view property

Viewed 1933

I'm trying to build a react-native application with a some native UI components and some React components. I want a native ui component which takes a react component as a property, and renders it as a subview.

I went through the normal process of making a native ui component and used RCT_EXPORT_VIEW_PROPERTY(view, RCTView) to get the view property.

PagedUIViewManager.swift:

@objc(PagedUIViewManager)
class PagedUIViewManager: RCTViewManager {
  override func view() -> UIView! {
    return PagedUIView();
  }
  override static func requiresMainQueueSetup() -> Bool {
    return true
  }
}

PagedUIView.swift:

class PagedUIView: UIView {
  @objc var view: UIView {
    didSet {
      for subview in self.subviews {
        subview.removeFromSuperview()
      }
      self.addSubview(view)
    }
  }
  override init(frame: CGRect) {
    self.view = UIView(frame: frame)
    super.init(frame: frame)
    self.addSubview(view)
  }
}

PagedUIViewManager.m:

#import "React/RCTViewManager.h"
@interface RCT_EXTERN_MODULE(PagedUIViewManager, RCTViewManager)
RCT_EXPORT_VIEW_PROPERTY(view, RCTView)
@end

PagedUINativeView.js:

const PagedUI = requireNativeComponent("PagedUIView");
export default class PagedUIView extends React.Component {
  render() {
    return <PagedUI {...this.props}/>;
  }
}

usage:

<PagedUIView view={<ComponentToRender />} />

I expected the view to show <ComponentToRender />, but instead I get the runtime error "Invariant Violation: 435,PagedView,1,[object Object] is not usable as a native method argument".

1 Answers

It currently no possible, the only way to pass views to native modules passing the view as children.

You can receive the view using:

@objc override func insertReactSubview(_ subview: UIView!, at atIndex: Int)
Related