-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
useCopied.tsx
22 lines (21 loc) · 908 Bytes
/
useCopied.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import copyTextToClipboard from '@uiw/copy-to-clipboard';
import { useCallback, useEffect } from 'react';
export function useCopied(container: React.RefObject<HTMLDivElement>) {
const handle = useCallback((event: Event) => {
const target = (event.currentTarget || event.target) as HTMLDivElement;
target.classList.add('active');
copyTextToClipboard(target.dataset.code as string, function () {
setTimeout(() => {
target.classList.remove('active');
}, 2000);
});
}, []);
useEffect(() => {
const btns = container.current?.querySelectorAll('pre code + div.copied');
btns && Array.from(btns).forEach((elm) => elm.addEventListener('click', handle, false));
return () => {
btns && Array.from(btns).forEach((elm) => elm.removeEventListener('click', handle, false));
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [container]);
}