useCopyToClipboard Hook
ReactJS
Hard
8 views
Problem Description
Create a hook to copy text to clipboard and show success state.
Output Format
Render a React component.
Constraints
Use navigator.clipboard when available and reset status after a delay.
Official Solution
import React, { useEffect, useState } from 'react';
function useCopyToClipboard(timeoutMs) {
const [status, setStatus] = useState('idle');
async function copy(text) {
try {
if (!navigator.clipboard) throw new Error('Clipboard not available');
await navigator.clipboard.writeText(text);
setStatus('copied');
} catch {
setStatus('error');
}
}
useEffect(() => {
if (status !== 'copied') return;
const id = setTimeout(() => setStatus('idle'), timeoutMs);
return () => clearTimeout(id);
}, [status, timeoutMs]);
return { status, copy };
}
export default function App() {
const [text, setText] = useState('https://meetcode.in');
const { status, copy } = useCopyToClipboard(1200);
return (
<div style={{ padding: 16, width: 560 }}>
<h2 style={{ marginTop: 0 }}>Copy link</h2>
<div style={{ display: 'flex', gap: 10 }}>
<input value={text} onChange={(e) => setText(e.target.value)} style={{ flex: 1, padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<button type='button' onClick={() => copy(text)} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Copy</button>
</div>
<div style={{ marginTop: 10, color: status === 'error' ? '#c1121f' : '#555' }}>
{status === 'idle' ? 'Click copy to test.' : null}
{status === 'copied' ? 'Copied!' : null}
{status === 'error' ? 'Copy failed in this browser.' : null}
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!