Creating a Component to display code snippet with copy to clipboard feature

Creating a Component to display code snippet with copy to clipboard feature

Many times we have come across a website where we can see the code snippet and on the left side there is cute little icon/text which allows us to copy that snippet to the clipboard.

Here is the step-by-step tutorial for making the same in React. Cause we love to React💓

Initially, we will build a minimal component with no fancy styles, just functionality. Then we will make it look cool.


Step 1 - Creating a Basic Structure for Component

In this step, we will create a box that will have the code and a button to copy the code. Something like this -

We will create a file CodeComponent.js for that.

export default function CopyComponent() {
  return (
    <div className="code-block">
      <span className="copy-btn">Copy</span>
      <code className="code-content">
        console.log("Hey There !")
      </code>
    </div>
  );
}

Add basic styles - styles.css

.code-content {
  margin-top: 30px;
}
.code-block {
  padding: 1rem;
  border: 1px solid #777;
  width: 50%;
  border-radius: 5px;
  position: relative;
}
.copy-btn {
  position: absolute;
  top: 0;
  right: 0;
  padding: 0.5rem;
  font-size: 12px;
  cursor: pointer;
}

PS - I have removed some styles from that, you can definitely add your own.

Step 2 - Adding functionality to the "Copy" Button

This is the crux of this article, how do we add copy to the clipboard feature

For this, we will use the - navigator.clipboard.writeText() method.

This function takes the input as a parameter.

Example -

navigator.clipboard.writeText("This will be copied to clipboard");

So, how do we get the code, there are many chances how you are passing the code to the component, for this example it will be static i.e. there will be code already present that will be copied.

for grabbing the text we will use ref .

Have a refresher about refs in React.

const codeRef = useRef();
const handleCopyBtnClick = (e) => {
   if (codeRef.current) {
     navigator.clipboard.writeText(codeRef.current.innerText);
   }
};

Add these lines before the return statement of CodeComponent.

handleCopyBtnClick() function grabs the code using the innerText method and puts it on the clipboard.

That's it. This is the simplest way of creating our desired component.

Step 3 - Beautification

To beautify the code we will add react-syntax-highlighter it to our app from npm.

After adding it to our code then CodeComponent.js becomes -

import { useRef, useState } from "react";
import SyntaxHighlighter from "react-syntax-highlighter";
import { docco as style } from "react-syntax-highlighter/dist/esm/styles/prism";

export default function CopyComponent() {
  const codeRef = useRef();
  const [copy, setCopy] = useState(false);
  const handleCopyBtnClick = (e) => {
    if (codeRef.current) {
      navigator.clipboard.writeText(codeRef.current.innerText);
      // Exercise - add logic to handle copy button text 
    }
  };
  return (
    <div className="code-block">
      <span className="copy-btn" onClick={handleCopyBtnClick}>
        {copy ? "Copied" : "Copy"}
      </span>
      <div ref={codeRef} style={{ borderRadius: "inherit" }}>
        <SyntaxHighlighter
          language="javascript"
          style={style}
          customStyle={{ margin: 0, borderRadius: "inherit", padding: "1rem" }}
        >
          console.log("Hello");
        </SyntaxHighlighter>
      </div>
    </div>
  );
}

🚨 Can you spot the comment?

I have a task for you, add logic for handling the text. The behavior should be, when I click the "Copy" button, it changes to "Copied", after some time it changes to "Copy".

It becomes like this -

PS - I have changed the CSS files as well.

View the code files - https://github.com/BhuvaneshPatil/code-block-with-copy

Here is the code sandbox, try to play around with it -

Hope you liked this mini tutorial. Follow me on Twitter for more.

Thank You.