Skip to content

Commit 60a9110

Browse files
committed
Add copy button
1 parent 884ce9d commit 60a9110

File tree

1 file changed

+33
-9
lines changed

1 file changed

+33
-9
lines changed

components/CodeBlock.js

+33-9
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,42 @@
1-
import React from 'react';
1+
import { useState } from 'react';
2+
import { ClipboardListIcon } from '@heroicons/react/outline';
3+
import { ClipboardCheckIcon } from '@heroicons/react/solid';
24
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
35
import { prism } from 'react-syntax-highlighter/dist/cjs/styles/prism';
46

57
const CodeBlock = {
68
code({ node, inline, className, children, ...props }) {
9+
const [copied, setCopied] = useState(false);
710
const match = /language-(\w+)/.exec(className || '');
8-
return !inline && match ? (
9-
<SyntaxHighlighter style={prism} language={match[1]} {...props}>
10-
{String(children).replace(/\n$/, '')}
11-
</SyntaxHighlighter>
12-
) : (
13-
<code className={className} {...props}>
14-
{children}
15-
</code>
11+
const code = String(children).replace(/\n$/, '');
12+
const codeBlock =
13+
!inline && match ? (
14+
<SyntaxHighlighter style={prism} language={match[1]} {...props}>
15+
{code}
16+
</SyntaxHighlighter>
17+
) : (
18+
<code className={className} {...props}>
19+
{children}
20+
</code>
21+
);
22+
23+
return (
24+
<div className="relative">
25+
{codeBlock}
26+
<button
27+
className="absolute top-1 right-1 p-2 bg-gray-100 rounded"
28+
onClick={() => {
29+
navigator.clipboard.writeText(code);
30+
setCopied(true);
31+
}}
32+
>
33+
{copied ? (
34+
<ClipboardCheckIcon className="h-5 w-5 text-green-500" />
35+
) : (
36+
<ClipboardListIcon className="h-5 w-5 text-black" />
37+
)}
38+
</button>
39+
</div>
1640
);
1741
},
1842
};

0 commit comments

Comments
 (0)