How to Copy to Clipboard in Lightning web component
Do you want to give users the ability to copy text to the clipboard from a Lightning web component? Here’s how you can do that.
In this simple example, the Lightning web component contains both a link & lightning button icon that will copy text when clicked. Here, I’ve put the text I want to copy in the name attribute of the “a” and “lightning-button-icon” tags. This could also be a variable.
<template> <!-- Simple Link --> <a onclick="handleCopyText" name="Text to Copy">Copy to Clipboard</a> <!--Lightning icon button--> <lightning-button-icon icon-name="utility:copy_to_clipboard" variant="border-filled" alternative-text="Copy To Clipboard" onclick={handleCopyText} name="Text to Copy"></lightning-button-icon> </template>
The handleCopyText method kicks off the action. First, extract the text you want to copy from the event. The steps to copy the text to clipboard are based on a solution I found here (this is using an aura component). In order to copy text, you create a hidden text element in the DOM, select & copy it, then remove it from the DOM again. I decided to make my text element a “textarea” tag because it respects line breaks, which was a requirement for my use case.
Lastly, the Lightning web component Javascript method shows a success message in a toast component. The toast disappears after 3 seconds or when dismissed.
import { LightningElement, api } from 'lwc'; import { ShowToastEvent } from 'lightning/platformShowToastEvent'; export default class MyCopyComponent extends LightningElement{ @api recordId; handleCopyText(event){ // get the text to copy let textToCopy = event.target.name; // create hidden input variable let hiddenInput = document.createElement("textarea"); hiddenInput.innerHTML = textToCopy; document.body.appendChild(hiddenInput); //execute copy command hiddenInput.select(); document.execCommand("copy"); // discard hidden input document.body.removeChild(hiddenInput); // show a success toast this.dispatchEvent( new ShowToastEvent({ title: 'Copied Text', message: '', variant: 'success' }) ); } }
Other than creating a “textarea” tag and using innerHTML to populate the text to copy, there are other ways to achieve it like
let hiddenInput = document.createElement("input");
hiddenInput.setAttribute("value", text);
Want to read more blog entries about Salesforce development? Follow me.