Kureev Alexey on how to use SwiftUI Components in an React Native App.
Today, we’ll write a proxy that allows developers to use SwiftUI in their React Native applications.
The Native SwiftUI Button Component looks like this:
struct SwiftUIButton : View {
@ObservedObject var props = ButtonProps()
var body: some View {
VStack {
Text("Count \(props.count)")
.padding()
Button(action: {
self.props.onCountChange(["count": self.props.count + 1])
}) {
Image(systemName: "plus.circle.fill")
.foregroundColor(.white)
.padding()
.background(Color.red)
.clipShape(Circle())
}
}
.padding()
.clipShape(Circle())
}
}
You’d then use like you’d use any other Native Component:
import React, {useState} from 'react';
import {requireNativeComponent} from 'react-native';
const SwiftUIButton = requireNativeComponent('SwiftUIButton');
const App = () => {
const [count, updateCount] = useState(0);
return (
<SwiftUIButton
style={styles.container}
count={count}
onCountChange={e => updateCount(e.nativeEvent.count)}
/>
);
};
To make it work he created two new macros to use: RCT_EXPORT_SWIFTUI_PROPERTY
and RCT_EXPORT_SWIFTUI_CALLBACK
.
React Native Meets SwiftUI →
ReactNativeWithSwiftUITutorial Repository →
Building further upon the code, some nice integrations have already been made. Such as this one:
#SwiftUI or #ReactNative ? Maybe you don't have to choose 😮
Animating @MengTo SwiftUI cards from you react-native app is amazing 😎 pic.twitter.com/p8v5ep596w
— Pierre Caporossi (@PierreCaporossi) February 14, 2020