In a previous post, Add a COPY Button to Syntax Highlighter, we added a COPY button using a bit of a workaround. Back then, the differences between server components and client components felt like a riddle wrapped in an enigma.
Initially, I created a separate component (CopyButton
) to handle the button. This component received the code as a prop and worked as a client component. But, let's be honest, it was a bit of a hack. You essentially ended up with two copies of the same text (the code and the button).
Now, with the wonders of use client
, we can make this process much smoother. Instead of sending a copy of the code around like a hot potato, let's use selectors to grab the code element directly and copy its contents. Sound good? Let's dive in.
'use client' import { FC } from "react" const CopyButton: FC = () => { return <a className='copyButton' onClick={(e) => { // Navigate up to the parent element const parentElement = e.currentTarget.parentElement; // Find the <pre> tag within the parent element const preElement = parentElement?.querySelector('pre'); // Assuming the <code> tag is directly within <pre> const codeElement = preElement?.querySelector('code'); if (codeElement) { navigator.clipboard.writeText(codeElement.textContent || ''); } }}> Copy </a> } export default CopyButton
Event Handling: Use the onClick
event. This will navigate to the parent element, find the <pre>
tag, and then the <code>
tag within it. If the code element is found, it's copied to the clipboard.
Testing: Make sure to test your new button to ensure it copies the code correctly.
And there you have it! A neater, more efficient COPY button that's ready for action. So next time you need to copy some code quickly, you'll be prepared to do it without breaking a sweat.
Happy coding, and may your clipboard always be full!
We use cookies to improve your experience and analyze our traffic. By using our site, you consent to our use of cookies. You can manage your preferences below: