javascriptreactjsreact-nativeclipboard

Error setting and getting text from Clipboard


import React, { useState } from 'react'
import { SafeAreaView, View, Text, TouchableOpacity, StyleSheet } from 'react-native'
import Clipboard from '@react-native-community/clipboard'

const App = () => {
    const [copiedText, setCopiedText] = useState('')

    const copyToClipboard = () => {
        Clipboard.setString('hello world')
    }

    const fetchCopiedText = async () => {
        const text = await Clipboard.getString()
        setCopiedText(text)
    }

    return (
        <SafeAreaView style={{ flex: 1 }}>
            <View style={styles.container}>
                <TouchableOpacity onPress={() => copyToClipboard()}>
                    <Text>Click here to copy to Clipboard</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => fetchCopiedText()}>
                    <Text>View copied text</Text>
                </TouchableOpacity>

                <Text style={styles.copiedText}>{copiedText}</Text>
            </View>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
//styles
})

export default App

When pressing "copy to clipboard", I get an error:

TypeError: null is not an object (evaluating 'NativeClipboard_1.default.setString')

and upon pressing "view copied text", I get another error:

TypeError: Unhandled promise rejection.

This code was copied directly from here: https://github.com/react-native-community/clipboard

screenshot of error


Solution

  • Use react clipboard

    Running example: https://snack.expo.io/@msbot01/4c673f

    code:

    import React, { useState } from 'react'
    import { SafeAreaView, View, Text, TouchableOpacity, Clipboard, StyleSheet } from 'react-native'
    
    const App = () => {
      const [copiedText, setCopiedText] = useState('')
    
      const copyToClipboard = () => {
        Clipboard.setString('hello world')
      }
    
      const fetchCopiedText = async () => {
        const text = await Clipboard.getString() 
        setCopiedText(text)
      }
    
      return (
        <SafeAreaView style={{ flex: 1 }}>
          <View style={styles.container}>
            <TouchableOpacity onPress={() => copyToClipboard()}>
              <Text>Click here to copy to Clipboard</Text>
            </TouchableOpacity>
            <TouchableOpacity style={{marginTop:50}} onPress={() => fetchCopiedText()}>
              <Text>Click to View copied text</Text>
            </TouchableOpacity>
    
            <Text style={styles.copiedText}>{copiedText}</Text>
          </View>
    
        </SafeAreaView>
      ) 
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      },
      copiedText: {
        marginTop: 10,
        color: 'red'
      }
    })
    
    export default App