- Install below Packages
bun i react-copy-to-clipboard lucide-react
- Create a
Copy.jsx
file
import React, { useState, useEffect } from "react";
import { CheckCheck, Copy } from "lucide-react";
import { CopyToClipboard } from "react-copy-to-clipboard";
const CopyButton = ({ output }) => {
const [copied, setCopied] = useState(false); // state for copied status
useEffect(() => {
if (copied) {
// Set a timeout to reset the copied state after 5 seconds
const timer = setTimeout(() => setCopied(false), 5000);
return () => clearTimeout(timer); // Clear timeout on unmount or when copied changes
}
}, [copied]);
return (
<CopyToClipboard
text={output}
onCopy={() => setCopied(true)} // set copied status to true on copy
>
<button className="inline-flex items-center border-gray-300 bg-white hover:bg-gray-50 shadow-sm px-4 py-2 border rounded-md focus:ring-2 focus:ring-primary focus:ring-offset-2 font-medium text-gray-700 text-sm focus:outline-none">
{copied ? (
<span className="flex">
<CheckCheck className="mr-2 w-5 h-5" /> Copied
</span>
) : (
<span className="flex">
<Copy className="mr-2 w-5 h-5" /> Copy
</span>
)}
</button>
</CopyToClipboard>
);
};
export default CopyButton;
- On your Output.jsx file
import React, { useState } from "react";
function Output() {
const [output, setValue] = useState(""); // Move state to Main
return (
<div className="p-4">
{/* Input field moved to Main */}
<input
value={output}
onChange={({ target: { value } }) => setValue(value)} // Update state in Main
className="p-2 border"
placeholder="Enter text to copy"
/>
{/* Pass output and setValue as props to App */}
<CopyButton output={output} setValue={setValue} />
</div>
);
}
export default Output;