Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass UIImage to RCTRootView

I'm working on a hybrid ios native/react-native project.

Let's say I have an instance of UIImage at some point in my app. I need to display this image in my react-native component. I create an RCTRootView like this:

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                  moduleName:@"SomeScreen"
                                           initialProperties:someParameters
                                               launchOptions:launchOptions];

What do I do next? Facebook describes how to use the <Image> component with uri, addressing an image in local file system or in Web. But I don't want to download it twice (also I don't want to reimplement authentication in react-native).

Is there any way to pass already existing UIImage to react-native component?

like image 672
illyge Avatar asked Feb 28 '17 16:02

illyge


1 Answers

I know the code in OP's question is in Obj-C but I was working on this using Java (and this question is already 2 years old). If you're using Obj-C translate this code from Swift to Obj-C as it should work.

What I did to send image data from my Native (Swift) application to my RN app was:

I sent the image as a base 64 encoded String by doing this:

//Add more images as needed
let images = [UIImage(named: "myImage")?.pngData()?.base64EncodedString()]
let props: [String : [String?]] = [
    "images": images //Remember this key
]
let rootView = RCTRootView(
    bundleURL: jsCodeLocation,
    moduleName: "RNHelloWorld",
    initialProperties: props,
    launchOptions: nil
)

Then, on your RN class do this:

export default class MyClass extends React.Component {
    renderImage(encodedImage) {
        //You need to manually specify widht and height
        //And decode your image as a base 64 image
        return <Image style={width: 50, height: 50} source={{uri: `data:image/png;base64,${encodedImage}`}} />
    }
    render() {
        //Use the same name as in your props key in Swift
        return <View>{this.props.images.map(this.renderImage}</View>
    }
}

Then, you're good to go.

like image 159
Frakcool Avatar answered Oct 28 '22 17:10

Frakcool