Create brownfield view as Fragment on Android
Igor Adrov
Hi! 👋
From the documentation, it looks like there is a very convenient way to create multiple views with different parameters on iOS:
However, I'm having trouble understanding how to achieve a couple of things on Android:
- Create a React Native instance as an Android Fragment (we need to integrate RN inside an existing native screen, so showReactNativeFragmentdoesn't seem like the right approach).
- Pass the component name and arguments on Android (the same values that are passed to AppRegistry.registerComponent).
Could you please clarify how this is expected to work on Android?
Thank you!
Gabriel Donadel
Hi Igor Adrov,
The template file
packages/expo-brownfield/plugin/templates/android/ReactNativeFragment.kt
provides the Fragment implementation. Instead of using showReactNativeFragment()
(which calls setContentView
and takes over the whole screen), use the lower-level APIs directly:// In your existing Activity/Fragment, embed the RN fragment into a specific container:
// First, ensure ReactNativeHostManager is initialized
ReactNativeHostManager.shared.initialize(application)
// Then create and commit the fragment into YOUR container (not as content view)
val container = ReactNativeFragment.createFragmentHost(
activity = this,
rootComponent = "MyComponentName" // defaults to "main"
)
// Add the container to your existing layout instead of setContentView
yourExistingLayout.addView(container)
Or for more control, use
createAndCommit
directly with your own container ViewGroup:val myContainer = FrameLayout(this).apply { id = View.generateViewId() }
yourExistingLayout.addView(myContainer)
ReactNativeFragment.createAndCommit(
activity = this,
container = myContainer,
rootComponent = "MyComponentName"
)
Passing component name and initial props
Component name is passed as the
rootComponent
parameter. This corresponds to the name registered via AppRegistry.registerComponent(name, ...)
on the JS side.Initial props (launch options) are supported at the factory level in
ReactNativeViewFactory.kt
:ReactNativeViewFactory.createFrameLayout(
context = this,
activity = this,
rootComponent = "MyComponentName",
launchOptions = Bundle().apply {
putString("userId", "123")
putInt("count", 42)
putBoolean("darkMode", true)
}
)