Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Access The Native Device Clipboard In React Native

TwitterFacebookRedditLinkedInHacker News

Keeping up the trend of React Native coolness, I figured it would be a good idea to see how to access the native device clipboard. I had already demonstrated the device clipboard with Ionic Framework so it would only be fair to accomplish the same with React Native as well.

Out of the box with React Native you won’t be able to access the clipboard. You’re going to have to install a component, and lucky for us, one such component exists. We are going to check out the react-native-clipboard component by Fishfly.

It is important to note that at the time of writing this tutorial, React Native is only (mostly) for iOS. This means that you’re going to need a Mac to accomplish everything.

With that said, open your Terminal and execute the following command:

react-native init ReactProject

Navigate into the fresh project with your Terminal and execute the following to install the clipboard component:

npm install react-native-clipboard --save

The component still needs to be configured in Xcode before it can be used. Open Xcode and right-click on Libraries in the project tree. Choose Add Files to “ReactProject”… and open your project’s node_modules/react-native-clipboard/RNClipboard.xcodeproj file. With that file added to your project, visit the Build Phases tab in Xcode and add libRNClipboard.a from the Link Binary With Libraries dialog.

More information on how to add components to your project can be found in the official React Native documentation.

Before we get down to coding let’s think about what’s going to happen. We’re going to create a very simple React Native application that has a ListView with two constant list items. When you long-press one of these list items it will copy it to the device clipboard. To prove that it copied we will pull the clipboard and print it in the logs.

To see this in action, open your project’s index.ios.js file and add the following code:

"use strict";

var React = require("react-native");
var Clipboard = require("react-native-clipboard");

var {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ListView,
    TouchableHighlight,
    NavigatorIOS,
    StatusBarIOS,
} = React;

var ReactProject = React.createClass({

    getInitialState: function() {
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        return {
            dataSource: ds.cloneWithRows(['row 1', 'row 2']),
        };
    },

    render: function() {
        return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
                style={styles.listView} />
        );
    },

    renderRow: function(row) {
        return (
            <TouchableHighlight onLongPress={() => this.copyRow(row)}>
                <View style={styles.container}>
                    <Text>{row}</Text>
                </View>
            </TouchableHighlight>
        );
    },

    copyRow: function(value) {
        Clipboard.set(value);
        Clipboard.get(content => console.log("Clipboard Content: " + content));
    }

});

var styles = StyleSheet.create({
    listView: {
        backgroundColor: '#F5FCFF',
    },
    container: {
        flex: 1,
        paddingTop: 15,
        paddingBottom: 15,
        flexDirection: "row",
        backgroundColor: '#F5FCFF',
        borderWidth: 1,
        borderTopColor: "white",
        borderRightColor: "white",
        borderLeftColor: "white",
        borderBottomColor: "#e0e0e0"
    }
});

AppRegistry.registerComponent('ReactProject', () => ReactProject);

Above is a lot to take in so I’m going to break it down into parts.

var Clipboard = require("react-native-clipboard");

The above line will make the component accessible to our JavaScript code. Everything will now be accessed through the Clipboard object.

Inside the ReactProject class we have the following function:

getInitialState: function() {
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
        dataSource: ds.cloneWithRows(['row 1', 'row 2']),
    };
}

It gets called when the application starts. The getInitialState function is responsible for initializing our ListView with dummy rows in our case.

render: function() {
    return (
        <ListView
            dataSource={this.state.dataSource}
            renderRow={this.renderRow}
            style={styles.listView} />
    );
}

The render function above will render our ListView to the screen. This view will take the two rows of data and display them. The two rows will be rendered through the renderRow function to keep things clean in our code. The renderRow function looks like the following:

renderRow: function(row) {
    return (
        <TouchableHighlight onLongPress={() => this.copyRow(row)}>
            <View style={styles.container}>
                <Text>{row}</Text>
            </View>
        </TouchableHighlight>
    );
}

The renderRow function accepts a row as a parameter. A TouchableHighlight is used so that way we can accept clicks. When a long-press happens, the copyRow function is called, passing in the particular row that was clicked.

copyRow: function(value) {
    Clipboard.set(value);
    Clipboard.get(content => console.log("Clipboard Content: " + content));
}

Above is where the actual component gets used. We are setting the clipboard to the value of the row that was passed and then immediately getting it and printing it to show it was stored.

Everything else in our index.ios.js file such as styling is not really important to us for this example.

Conclusion

Through the use of a third-party component, we can access the native device clipboard to save or load data in React Native. This can be useful in many scenarios like copying content from areas that are not user editable.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.