import React, { useEffect, useState } from 'react'; import Fade from '@/components/elements/Fade'; import Portal from '@/components/elements/Portal'; import copy from 'copy-to-clipboard'; import classNames from 'classnames'; const CopyOnClick: React.FC<{ text: string | number | null | undefined }> = ({ text, children }) => { const [copied, setCopied] = useState(false); useEffect(() => { if (!copied) return; const timeout = setTimeout(() => { setCopied(false); }, 2500); return () => { clearTimeout(timeout); }; }, [copied]); if (!React.isValidElement(children)) { throw new Error('Component passed to must be a valid React element.'); } const child = !text ? React.Children.only(children) : React.cloneElement(React.Children.only(children), { className: classNames(children.props.className || '', 'cursor-pointer'), onClick: (e: React.MouseEvent) => { copy(String(text)); setCopied(true); if (typeof children.props.onClick === 'function') { children.props.onClick(e); } }, }); return ( <> {copied && ( Copied "{text}" to clipboard. )} {child} > ); }; export default CopyOnClick;
Copied "{text}" to clipboard.