React + Markdown: How to add a copy to clipboard button to code blocks

Posted on: 2021-12-04

There are several ways you can add a "copy to clipboard" button to a code block when markdown in your react app... here I'm sharing what seems to be the most straightforward approach. We are using two libraries: react-markdown and react-clipboard-button (I'm the author of this last one, I actually made it for this very website). Though it's not mandatory, in this example I'll also add highlight.js for synthax highlighting.

import { CopyToClipboardWrapper } from 'react-clipboard-button'; import ReactMarkdown from 'react-markdown'; import hljs from 'highlight.js'; //... <ReactMarkdown children={markdownString} components={{ pre({node, ...props }) { return <pre {...props} className="hljs"/>}, code({node, inline, className, children, ...props}) { const match = /language-(\w+)/.exec(className || ''); return !inline && match ? ( <CopyToClipboardWrapper text={String(children)} onSuccess={() => toast.success('Copied to clipboard')}// if you are using a toaster library style={{}} > <code {...props} className={`${className} language-${match[1]}`} dangerouslySetInnerHTML={{ __html: hljs.highlight(String(children), { language: match[1], ignoreIllegals: true }).value }}> </code> </CopyToClipboardWrapper> ) : ( <code className={className} {...props}> {children} </code> ) } }} /> // ...