Open In App

How to Copy Text to the Clipboard in React Native ?

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Mobile app de­velopment requires enabling text copying to the clipboard for se­amless content sharing and improved use­r experience­. A popular cross-platform framework, React Native, offers a solution to this common requirement. This article will guide develope­rs through implementing clipboard functionality using the @re­act-native-clipboard/clipboard package. By handling text input, utilizing the Clipboard API, and providing user feedback, users can effortlessly copy and share text within or across applications. Enhancing usability and empowering users to interact efficiently with content in Re­act Native apps only requires a few lines of code.

Prerequisites:

Steps to Create React Native Application:

Step 1: Create React Native Application With Expo CLI

Using Expo CLI, run the following command to create a new React native application:

npx create-expo-app ClipboardApp

Step 2: ​Navigate to the project directory by using this command:

cd ClipboardApp

Project Structure:

React-Native-Project-Structure

Approach:

  • Firstly, a React Native proje­ct is set up with all the nece­ssary dependencie­s, including the `@react-native-clipboard/clipboard` package­.
  • Then, a screen is cre­ated featuring an input field for capturing the­ text and a “Copy” button to initiate the copying proce­ss.
  • Upon pressing the button, the `Clipboard.se­tString()` method is called to store the­ text in the clipboard. To provide use­r feedback based on the­ir platform (iOS/Android), either `ToastAndroid` or `Alert` compone­nts are utilized.

Example: In this example, we will see copy text to the clipboard in React Native.

  • App.js

Javascript




import React, { useState } from 'react';
import {
    View,
    Text,
    TextInput,
    TouchableOpacity,
    Clipboard,
    ToastAndroid, // For Android-specific toast message
    AlertIOS,     // For iOS-specific alert message
    Platform      // To handle cross-platform differences
} from 'react-native';
  
const App = () => {
    const [copyText, setCopyText] = useState('');
    const [copied, setCopied] = useState(false);
  
    const handleCopyText = (text) => {
        setCopyText(text);
        setCopied(false);
    };
  
    const copyToClipboard = () => {
        if (copyText) {
            Clipboard.setString(copyText);
  
            // Display a success message
            if (Platform.OS === 'android') {
                ToastAndroid.show('Text copied to clipboard!',
                    ToastAndroid.SHORT);
            } else if (Platform.OS === 'ios') {
                AlertIOS.alert('Text copied to clipboard!');
            }
  
            setCopied(true);
        }
    };
  
    const containerStyle = {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 40,
    };
  
    const headingStyle = {
        fontSize: 32,
        fontWeight: 'bold',
        marginBottom: 20,
    };
  
    const inputStyle = {
        padding: 10,
        marginBottom: 20,
        borderWidth: 2,
        borderColor: 'green',
        borderRadius: 4,
        width: 300,
        fontSize: 16,
        margin: 10,
    };
  
    const buttonStyle = {
        backgroundColor: 'green',
        color: 'white',
        padding: 10,
        borderRadius: 4,
        fontSize: 16,
    };
  
    const successMessageStyle = {
        color: 'green',
        marginTop: 10,
    };
  
    return (
        <View style={containerStyle}>
            <Text style={headingStyle}>
                Copy Text to Clipboard
            </Text>
            <TextInput
                value={copyText}
                onChangeText={handleCopyText}
                style={inputStyle}
                placeholder="Enter the text you want to copy"
            />
            <TouchableOpacity onPress={copyToClipboard}
                style={buttonStyle}>
                <Text style={{ color: 'white' }}>
                    Copy
                </Text>
            </TouchableOpacity>
            {copied &&
                <Text style={successMessageStyle}>
                    Text copied to clipboard!
                </Text>}
  
            <TextInput
                style={inputStyle}
                placeholder="Enter the copied text"
            />
        </View>
    );
};
  
export default App;


Step 4: To run the React Native application, open the Terminal or Command Prompt and type the following command:

npx expo start

To run on Android:

npx react-native run-android

To run on Ios:

npx react-native run-ios

Output:

How-To-Copy-Text-To-The-Clipboard-In-React-native

How To Copy Text To The Clipboard In React Native?



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads