search
HomeWeb Front-endFront-end Q&AHow to implement copy function in react

How to implement the copy function in react: 1. Implement the copy function through the "copy-to-clipboard" library; 2. Use the "react-copy-to-clipboard" library to implement the copy function; 3. Through the "navigator" .clipboard.writeText(e)" method to realize copying; 4. To realize copying through "document.execcommand("copy")" method; 5. To realize copy function through "copy-js" library.

How to implement copy function in react

## The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

#How to implement the copy function in react?

One-click copying in React - five methods

    copy-to-clipboard library (recommended)
  • react-copy-to-clipboard library (recommended)
  • navigator.clipboard.writeText(e) (recommended)
  • document.execcommand("copy")
  • copy- js library

copy-to-clipboard

1. Installation method

// npm安装---这种方式可能会对babel的版本有限制
npm i --save copy-to-clipboard


//cdn引入
<script src="https://wzrd.in/standalone/copy-to-clipboard@latest" async></script>

2. Usage method

import copy from 'copy-to-clipboard';const handleClick = ()=>{
	copy('复制的内容');
	message.success('复制成功')}<button>复制</button>

react-copy-to-clipboard

This method is based on copy-to-clipboard. If you find that there are version restrictions with other npm packages when installing copy-to-clipboard If so, then this probably won't work, but it's not impossible to try

1. Installation

npm i --save react-copy-to-clipboard
2. Usage - there is a place

to pay attention to, in , there can only be one root element, and I tried it myself, if in , a root element is wrapped If there are two sibling nodes such as a div and a button, the copy will not take effect. I don't know why. Interested friends can check out the source code.

import { CopyToClipboard } from 'react-copy-to-clipboard';

 <copytoclipboard> {
     if (result) {
       message.success('复制成功');
     } else {
       message.error('复制失败,请稍后再试');
     }
   }}
 >
   <button></button>}
   />
 </copytoclipboard>

document.execcommand("copy")——has been deprecated

But it seems that some browsers can still use it, see the document

for details I I have never used this method, and I don’t know what the pitfalls are.

How to use

<button>一键复制</button>const btn = document.querySelector('#btn');
  btn.addEventListener('click', () => {
      const textarea= document.createElement('textarea');
      textarea.setAttribute('readonly', 'readonly');
      textarea.value = 'xxxxx';
      document.body.appendChild(textarea);
      textarea.select();
      if (document.execCommand('copy')) {
          document.execCommand('copy');
          alert('复制成功');
      }
      document.body.removeChild(textarea);
  })

copy-js library

I just found this library and have never used it, but I looked at the bottom of the source code Also used

document.execcommand("copy") 1. Install

// npm包下载npm install copy-js --save// CDN导入<script></script>
2. Use

import copy from 'copy-to-clipboard';copy('hello world', function(err) {
    if (err) console.log('Some thing went wrong!');
 
    console.log('Copied!');});

navigator.clipboard. writeText(e)

This method also has pitfalls. The development time is relatively short, and there is no specific study of the reasons.

The parameter e of this method needs to get the value of the input text box and copy it. Node

However, this method may have limitations in the in-end browser of some applications. It can be used in normal browsers, but for example, it is now available in the Feishu end-end browser. There is no clipboard object. It still depends on the usage scenario.

1. How to use

const { Search } = Input;const copyLink = (e: any) => {
  navigator.clipboard.writeText(e).then(
    () => {
      message.success(intl.t('复制成功'));
      console.log(e);
    },
    () => {
      message.error(intl.t('复制失败,请稍后再试'));
    },
  );};


 <search></search>
There may be other methods that I haven’t thought of yet

Recommended learning: "

react video tutorial

The above is the detailed content of How to implement copy function in react. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.