Skip to content

SwiftUI Root

The SwiftUI component is the root container that bridges React Native and SwiftUI. All SwiftUI components must be descendants of this container.

import { SwiftUI } from '@mgcrea/react-native-swiftui';
import { SwiftUI } from '@mgcrea/react-native-swiftui';
import { View } from 'react-native';
export function MyComponent() {
return (
<View style={{ flex: 1 }}>
<SwiftUI style={{ flex: 1 }}>
<SwiftUI.Text text="Hello SwiftUI!" />
</SwiftUI>
</View>
);
}
PropTypeDefaultDescription
idstringAuto-generatedCustom identifier for the root
styleStyleProp<ViewStyle>-Style applied to the native container
debugbooleanfalseEnable debug logging for component tree
onEvent(event: { nativeEvent: NativeSwiftUIEvent }) => void-Raw event handler for all events
childrenReactNode-SwiftUI components to render

Enable debug mode to log the component tree and events:

<SwiftUI style={{ flex: 1 }} debug>
<SwiftUI.Form>
<SwiftUI.TextField label="Name" text={name} onChange={setName} />
</SwiftUI.Form>
</SwiftUI>

This will log:

  • Component registration/unregistration
  • View tree structure
  • Event dispatches

The onEvent prop receives all events from the SwiftUI tree:

<SwiftUI
style={{ flex: 1 }}
onEvent={(event) => {
console.log('Event:', event.nativeEvent);
// { type: 'change', id: 'textfield-1', value: 'Hello' }
}}
>
<SwiftUI.TextField label="Name" text={name} onChange={setName} />
</SwiftUI>

Events include:

  • change - Value changes
  • press - Button presses
  • focus - Field focus
  • blur - Field blur
  • dismiss - Sheet dismissal
  • primaryAction / secondaryAction - Sheet button actions

The root component accepts standard React Native ViewStyle:

<SwiftUI
style={{
flex: 1,
backgroundColor: '#f5f5f5',
padding: 16,
}}
>
{/* ... */}
</SwiftUI>

You can have multiple SwiftUI roots in your app, but they are independent:

<View style={{ flex: 1 }}>
<SwiftUI style={{ flex: 1 }}>
<SwiftUI.Form>{/* Form 1 */}</SwiftUI.Form>
</SwiftUI>
<SwiftUI style={{ flex: 1 }}>
<SwiftUI.Form>{/* Form 2 */}</SwiftUI.Form>
</SwiftUI>
</View>

Each root manages its own component tree and state.