fatuhoku
fatuhoku

Reputation: 4911

Get the content size of view React Native outputs?

React Native provides a view class called RCTRootView. You specify the frame in which the RootView should render things, and it goes ahead and does it.

In my use-case though, the size of the content view is dynamic, and depends on the data being passed into React Native. This size is important because I'm going to put the React Native view into e.g. a self-sizing cell.

How is this done?

Upvotes: 3

Views: 2956

Answers (1)

Luke Rhodes
Luke Rhodes

Reputation: 323

@fatuhoku I came to the same conclusion after some digging around. For anyone else who's looking to do this, here's an example.

  • Declare your bridge to native code where we'll be sending the content size (where depends on preference, I create the instance outside of any class/function at the top of the file).
  • Call a method in the onLayout property of a JSX component.
  • In the onLayout method being called, send the content size data to the bridge.
  • Use the content size in the native ObjC or Swift code as you need.

// MyReactComponent.jsx (ES6)

// Modules var React = require('react-native'); var { View } = React; // Bridge var ReactBridge = require('NativeModules').ReactBridge; // Type Definitions type LayoutEvent = { nativeEvent: { layout: { x: number; y: number; width: number; height: number; }; }; }; // React Component class MyReactComponent extends React.Component { onViewLayout(e: LayoutEvent) { ReactBridge.setLayout(e.nativeEvent.layout); } render() { return ( <View onLayout={ this.onViewLayout }> <ChildComponentExample /> </View> ); } }

Then in ObjC you use the RCT_EXPORT_METHOD as described in React Native's documentation to create the "ReactBridge" and handle the the data sent on the "setLayout" method. The data will be an NSDictionary in this case but you could just as easily send only the layout height and you'd then get a CGFloat.

Upvotes: 2

Related Questions