Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 448
Michael Steuer Avatar asked Jun 03 '17 19:06

Michael Steuer


People also ask

How do you do copy to clipboard in react native?

Set selectable prop of the Text component true and the content will be copied to the clipboard with long press on the text.

How do I paste from clipboard response?

You can paste using the keybind Ctrl + V while focus is on the grid.

How do I transfer data to clipboard?

Open the file that you want to copy items from. Select the first item that you want to copy, and press CTRL+C. Continue copying items from the same or other files until you have collected all of the items that you want. The Office Clipboard can hold up to 24 items.


1 Answers

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.

like image 61
Ihor Burlachenko Avatar answered Sep 19 '22 02:09

Ihor Burlachenko