-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathindex.tsx
56 lines (48 loc) · 1.24 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* External dependencies
*/
import React, { useState, useEffect, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import classNames from 'classnames';
/**
* Internal dependencies
*/
import './style.scss';
interface CopyButtonProps {
textToCopy: string;
label: string;
}
const CopyButton: React.FC< CopyButtonProps > = ( { textToCopy, label } ) => {
// useRef() is used to store the timer reference for the setTimeout() function.
const timerRef = useRef< NodeJS.Timeout | null >( null );
// useEffect() is used to clear the timer reference when the component is unmounted.
useEffect( () => {
return () => {
if ( timerRef.current ) {
clearTimeout( timerRef.current );
}
};
}, [] );
const [ copied, setCopied ] = useState( false );
const copyToClipboard = () => {
navigator.clipboard.writeText( textToCopy );
setCopied( true );
timerRef.current = setTimeout( () => {
setCopied( false );
}, 2000 );
};
return (
<button
type="button"
className={ classNames( 'woopayments-copy-button', {
'state--copied': copied,
} ) }
aria-label={ label }
title={ __( 'Copy to clipboard', 'woocommerce-payments' ) }
onClick={ copyToClipboard }
>
<i></i>
</button>
);
};
export default CopyButton;