노현진's Blog

Next.js 클립보드 복사 기능 구현 방법

Next.js 클립보드 복사 기능 구현 방법에 대해 정리한 페이지입니다.

Posted
By HyunJinNo

Tags

Clipboard, Next.js, React

1. 개요

Next.js 클립보드 복사 기능 구현 방법에 대해 정리한 페이지입니다.

2. 클립보드 복사 기능 구현하기

React 및 Next.js에서 클립보드 복사 기능은 브라우저의 Clipboard API를 사용해서 구현할 수 있습니다.

2.1. Step 1 - useClipboard 커스텀 훅 구현하기

Clipboard API는 클립보드 명령(잘라내기, 복사, 붙여넣기)에 응답하거나 시스템 클립보드에 비동기적으로 접근하고 쓸 수 있는 기능을 제공합니다. 먼저 다음과 같이 텍스트를 클립보드로 복사하는 커스텀 훅을 구현합니다. 클립보드 기능은 브라우저 기능이므로 "use client"를 사용해야 합니다.

typescript
1"use client";
2
3import { useState } from "react";
4
5export const useClipboard = () => {
6  const [copied, setCopied] = useState(false);
7
8  const copy = async (text: string) => {
9    try {
10      await navigator.clipboard.writeText(text);
11      setCopied(true);
12      setTimeout(() => setCopied(false), 2000);
13    } catch {
14      return false;
15    }
16  };
17
18  return { copied, copy };
19};

Caution

Clipboard API는 HTTPS 환경에서만 동작합니다.

2.2. Step 2 - CopyButton 구현하기

useClipboard 커스텀 훅 구현 이후에는 다음과 같이 재사용 가능한 CopyButton 컴포넌트를 구현합니다.

typescript
1"use client";
2
3import { useClipboard } from "@/shared/lib/hooks";
4import { FaCheck } from "@react-icons/all-files/fa/FaCheck";
5import { FaRegClipboard } from "@react-icons/all-files/fa/FaRegClipboard";
6
7interface CopyButtonProps {
8  text: string;
9}
10
11export const CopyButton = ({ text }: CopyButtonProps) => {
12  const { copied, copy } = useClipboard();
13
14  return (
15    <button
16      className="flex h-9 w-9 items-center justify-center text-base hover:text-teal-500"
17      onClick={() => copy(text)}
18    >
19      {copied ? <FaCheck className="text-teal-500" /> : <FaRegClipboard />}
20    </button>
21  );
22};

2.3. Step 3 - CopyButton 사용하기

구현한 클립보드 기능을 사용한 예시는 다음과 같습니다.

3. 참고 자료

This post is licensed under CC BY 4.0 by the author.
공유하기:

© HyunJinNo. Some rights reserved.