skip to Main Content

I’m using the following code for Copy-to-clipboard, and it’s coping the text with all formatting applied like (bold and white color text), I just want to copy the text without any formatting by clicking the button. Please suggest how could I get it.

import React from "react";
import { CopyIcon } from "lucide-react";
import { CopyToClipboard } from "react-copy-to-clipboard";
import { useToast } from "@/hooks/use-toast";

export default function Cod({ text }) {
  const { toast } = useToast();

  return (
    <div className="flex gap-2 mt-4">
      <pre className="dark:bg-background h-12 place-content-center rounded-md p-2">
        <code className="font-semibold text-foreground">{text}</code>
      </pre>
      <CopyToClipboard text={text} onCopy="">
        <button
          className="hover:bg-background p-1 rounded-md"
          onClick={() => {
            toast({ description: "Copy successful !" });
          }}
        >
          <CopyIcon size={18} />
        </button>
      </CopyToClipboard>
    </div>
  );
}

2

Answers


  1. To copy the plain text without formatting, you can use the textContent property of the DOM node instead of copying from a formatted element.

    import { CopyIcon } from "lucide-react";
    import { useToast } from "@/hooks/use-toast";
    
    export default function Cod({ text }) {
      const { toast } = useToast();
    
      const handleCopy = () => {
        // Copy the plain text
        navigator.clipboard.writeText(text).then(() => {
          toast({ description: "Copy successful!" });
        });
      };
    
      return (
        <div className="flex gap-2 mt-4">
          <pre className="dark:bg-background h-12 place-content-center rounded-md p-2">
            <code className="font-semibold text-foreground">{text}</code>
          </pre>
          <button
            className="hover:bg-background p-1 rounded-md"
            onClick={handleCopy}
          >
            <CopyIcon size={18} />
          </button>
        </div>
      );
    }```
    
    Login or Signup to reply.
  2. The package you are using provides an option to copy the plain text. You need to pass the options prop and set it to {format: 'text/plain'}.

    <CopyToClipboard text={text} onCopy="" options={{format: 'text/plain'}}>
      <button
        className="hover:bg-background p-1 rounded-md"
        onClick={() => {
          toast({ description: "Copy successful !" });
        }}
      >
        <CopyIcon size={18} />
      </button>
    </CopyToClipboard>
    

    Check this comment.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search