How to Start react-native inside of a fragment? While putting react-native inside Fragment, onCreateView function is unable to return View from mReactRootView.
View view = inflater.inflate(mReactRootView. , container, false);
How to Start react-native inside of a fragment? While putting react-native inside Fragment, onCreateView function is unable to return View from mReactRootView.
View view = inflater.inflate(mReactRootView. , container, false);
I've managed to figure this out with much trial and error. I've seen this question asked around the internet and thought that this was the best place to post the answer. Here is how to do with the latest version of React (0.29 as of this writing):
The first thing we'll do is create an abstract
ReactFragment
class that we will use throughout our app:We'll now be able to create fragments that render React Native components, e.g.:
A little more work is required, though. Our parent
Activity
needs to pass some things into theReactInstanceManager
in order for the React Native lifecycle to work properly. Here's what I ended up with:Finally, you'll notice the reference to
(MyApplication)
throughout the code; this is a globalApplication
object to contain ourReactInstanceManager
, AKA the bridge between Android and React Native. This is the pattern that the React Native projects use internally, so I simply copied it. Here's how it's implemented:The trickiest bit was figuring out the lifecycle between the Fragment and the Activity; the
ReactRootView
needs a reference to the Activity context in order to instantiate, so making sure thatgetActivity()
would not be null was important. Also, registering theonHostPause()
andonHostResume()
in the parent Activity was unintuitive at first, but ultimately proved simpler once theReactNativeInstanceManager
was abstracted away into a global instead of keeping it on the Activity or Fragment.Hope this helps someone else out there!
There are libraries available that handle this for you.
One that I use is react-native-android-fragment
As per the instructions on the linked GitHub repository:
compile 'com.github.hudl:react-native-android-fragment:v0.43.2'
.e.g.
Build you react code into the fragment
Fragment reactFragment = new ReactFragment.Builder() .setComponentName("HelloWorld") .setLaunchOptions(launchOptions) // A Bundle of launch options .build();
Place the Fragment in a FrameLayout that you would have in your XML layout file. In my case, the FrameLayout ID is react_holder.
getSupportFragmentManager() .beginTransaction() .add(R.id.react_holder, reactFragment) .commit();