Michael Steuer
Michael Steuer

Reputation: 517

React Native Clipboard - how to copy an image or anything other than text?

In React Native, with the Clipboard, how can I place an image in the Clipboard? The only method provided to set Clipboard content is "setString". Can you not set images or other content than strings?

Upvotes: 8

Views: 4090

Answers (1)

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4915

It is possible to bridge native iOS clipboard API and expose the setImage method. To do that you need:

  1. Add native module header file Clipboard.h:

#import "RCTBridgeModule.h"
@interface Clipboard : NSObject <RCTBridgeModule>
@end

  1. Add native module implementation file Clipboard.m. We needed to copy base64 encoded images but you can adjust the code use any other image representation:

#import <UIKit/UIKit.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "Clipboard.h"

@implementation Clipboard

RCT_EXPORT_MODULE(BetterClipboard); // this is how our native module will be named

RCT_EXPORT_METHOD(addBase64Image:(NSString *)base64Image) {
  UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  [pasteboard setPersistent:YES];
  
  NSData *imageData = [[NSData alloc]initWithBase64EncodedString:base64Image options:NSDataBase64DecodingIgnoreUnknownCharacters];

  [pasteboard setImage:[UIImage imageWithData:imageData]];
}

@end

  1. And then you can use it in your React application:

import { NativeModules } from 'react-native';
   
NativeModules.BetterClipboard.addBase64Image(base64EncodedImage);

Unfortunately, I don't know how to do the same for Android.

Upvotes: 9

Related Questions