Skip to content

Commit 1b9adeb

Browse files
committed
feat: implement dynamic Clipboard import and enhance error handling for copy functionality
1 parent 91a72dd commit 1b9adeb

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

src/CopyItem.tsx

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,46 +5,64 @@ import {
55
type StyleProp,
66
type ViewStyle,
77
} from 'react-native';
8-
import Clipboard from '@react-native-clipboard/clipboard';
98
import Icon from './Icon';
109

10+
let Clipboard: any = null;
11+
try {
12+
Clipboard = require('@react-native-clipboard/clipboard').default;
13+
} catch (error) {
14+
Clipboard = null;
15+
}
16+
1117
interface CopyItemProps {
1218
textToCopy: string;
1319
checkDuration?: number;
1420
style?: StyleProp<ViewStyle>;
21+
useCopyToClipboard?: boolean;
1522
}
1623

1724
export const CopyItem: React.FC<CopyItemProps> = ({
1825
textToCopy,
1926
checkDuration = 2000,
2027
style,
28+
useCopyToClipboard,
2129
}) => {
2230
const [copied, setCopied] = useState(false);
2331
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
2432

2533
useEffect(() => {
26-
return () => {
27-
if (timeoutRef.current) {
28-
clearTimeout(timeoutRef.current);
29-
}
30-
};
31-
}, []);
34+
if (useCopyToClipboard && !Clipboard) {
35+
throw new Error(
36+
'Copy to clipboard functionality is required (useCopyToClipboard=true) but @react-native-clipboard/clipboard module is not installed. Please install it with: npm install @react-native-clipboard/clipboard'
37+
);
38+
}
39+
}, [useCopyToClipboard]);
3240

3341
const handleCopy = useCallback(async () => {
42+
if (!useCopyToClipboard || !Clipboard) {
43+
return;
44+
}
3445
try {
35-
Clipboard.setString(textToCopy);
46+
Clipboard?.setString(textToCopy);
3647
setCopied(true);
3748
if (timeoutRef.current) {
3849
clearTimeout(timeoutRef.current);
3950
}
40-
4151
timeoutRef.current = setTimeout(() => {
4252
setCopied(false);
4353
}, checkDuration);
4454
} catch {
4555
Alert.alert('Failed to copy to clipboard');
4656
}
47-
}, [textToCopy, checkDuration]);
57+
}, [textToCopy, checkDuration, useCopyToClipboard]);
58+
59+
if (!useCopyToClipboard) {
60+
return null;
61+
}
62+
63+
if (!Clipboard) {
64+
return null;
65+
}
4866

4967
return (
5068
<TouchableOpacity
@@ -53,6 +71,7 @@ export const CopyItem: React.FC<CopyItemProps> = ({
5371
activeOpacity={0.5}
5472
accessibilityRole="button"
5573
accessibilityLabel={copied ? 'Copied to clipboard' : 'Copy to clipboard'}
74+
disabled={!useCopyToClipboard}
5675
>
5776
{copied ? <Icon type="done" /> : <Icon type="copy" />}
5877
</TouchableOpacity>

0 commit comments

Comments
 (0)