How to let users copy and paste the UI text?

I have an Ionic React v5 learning app and I want the users to be able to copy-and-paste the UI text.

On the PWA on desktop, you can simply highlight text and copy it to the keyboard.

But on iOS/Android, users can’t highlight the text to select it and copy.

I checked out the Capacitor clipboard plugin but this seems to be for letting the app read and write from the clipboard. I installed it and I still can’t select the text displayed in my app (for example, <IonContent><p>Some text.</p></IonContent>. How can I do this?

If you inspect the element you will see a Ionic css class that add styles that are responsible for this, like user-select: none and some more. You should add a new class to the text that you want to be able to copiyable and override/reset these styles.

Or (what i would prefer if this is possible with your UI):

Create a Input/Trxtarea that is readonly and contains your text

1 Like

Copy with selecting text by user is not user friendly (it’s always hard to select the text you want).
You can add button next to text or the text itself can be a button and on click run the next function and copy text and based on return value show message to user.

export const copyToClipboard = (str: string): boolean => {
  const el = document.createElement("textarea");
  el.value = str;
  el.setAttribute("readonly", "");
  // el.style = { position: "absolute", left: "-9999px" };
  document.body.appendChild(el);

  el.select();
  // Copy text to clipboard
  try {
    const successful = document.execCommand("copy");
    if (successful) {
      document.body.removeChild(el);
      return true;
    }
  } catch (err) {
    return false;
  }

  return false;
};
1 Like