Leave a star on GitHub! ⭐


Docs
Code Snippet

Code Snippet

A codesnippet from which we can copy commands

Installation

pnpm add lucide-react sooner

Copy and paste the following code into your project.

components/eldoraui/codesnippet.tsx

"use client";
import { ClipboardIcon } from "lucide-react";
import { toast } from "sonner";
import { useCopyToClipboard } from "@/components/hooks/copytoclipboard";
 
export function CommandCode({ children }: Readonly<{ children: string }>) {
  const [copiedText, copy] = useCopyToClipboard();
  const handleCopyCode = (_code: string) => {
    copy(children);
    toast.success(`Command copied: ${copiedText}`);
  };
  return (
    <button
      className="flex transform-gpu items-center justify-between gap-5 rounded-full bg-fuchsia-300/20 px-5 py-3 tracking-tighter text-fuchsia-800 transition-all hover:bg-fuchsia-300/15 active:scale-90 active:bg-fuchsia-300/30 dark:text-fuchsia-400"
      onClick={() => handleCopyCode(children)}
      type="button"
    >
      <code className=" truncate text-left">{children}</code>
      <ClipboardIcon className=" size-5" />
    </button>
  );
}

Copy and paste the following code into your project.

components/eldoraui/hooks/copytoclipboard.tsx

"use client";
import { useCallback, useEffect, useState } from "react";
 
type CopiedValue = string | null;
 
type CopyFn = (text: string) => Promise<boolean>;
 
export function useCopyToClipboard({
  isCopiedDelay = 2000,
}: {
  isCopiedDelay?: number;
} = {}): [CopiedValue, CopyFn, boolean] {
  const [copiedText, setCopiedText] = useState<CopiedValue>(null);
  const [isCopied, setIsCopied] = useState(false);
 
  useEffect(() => {
    if (!isCopied) {
      return;
    }
    setTimeout(() => {
      setIsCopied(false);
    }, isCopiedDelay);
  }, [isCopied, isCopiedDelay]);
 
  const copy: CopyFn = useCallback(async (text) => {
    if (!navigator?.clipboard) {
      return false;
    }
 
    // Try to save to clipboard then save it in the state if worked
    try {
      await navigator.clipboard.writeText(text);
      setCopiedText(text);
      setIsCopied(true);
      return true;
    } catch (_error) {
      setCopiedText(null);
      return false;
    }
  }, []);
 
  return [copiedText, copy, isCopied];
}

Update the import paths to match your project setup.

Props

CommandCode Component Props

Prop NameTypeDefaultDescription
childrenstring-The command or code text that will be displayed and copied.