In reactJS, how to copy text to clipboard?

前端 未结 21 1969
刺人心
刺人心 2020-12-02 04:43

I\'m using ReactJS and when a user clicks a link I want to copy some text to the clipboard.

I am using Chrome 52 and I do not need to support any other browsers.

21条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 05:11

    Found best way to do it. i mean the fastest way: w3school

    https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

    Inside a react functional component. Create a function named handleCopy:

    function handleCopy() {
      // get the input Element ID. Save the reference into copyText
      var copyText = document.getElementById("mail")
      // select() will select all data from this input field filled  
      copyText.select()
      copyText.setSelectionRange(0, 99999)
      // execCommand() works just fine except IE 8. as w3schools mention
      document.execCommand("copy")
      // alert the copied value from text input
      alert(`Email copied: ${copyText.value} `)
    }
    
    <>
                  
                  
    
    
    

    If not using React, w3schools also have one cool way to do this with tooltip included: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_copy_clipboard2

    If using React, a cool think to do: Use a Toastify to alert the message. https://github.com/fkhadra/react-toastify This is the lib very easy to use. After installation, you may be able to change this line:

     alert(`Email copied: ${copyText.value} `)
    

    For something like:

    toast.success(`Email Copied: ${copyText.value} `)
    

    If you want to use it, dont forget to Install toastify. import ToastContainer and also toasts css:

    import { ToastContainer, toast } from "react-toastify"
    import "react-toastify/dist/ReactToastify.css"
    

    and add the toast container inside return.

    import React from "react"
    
    import { ToastContainer, toast } from "react-toastify"
    import "react-toastify/dist/ReactToastify.css"
    
    
    export default function Exemple() {
      function handleCopy() {
        var copyText = document.getElementById("mail")
        copyText.select()
        copyText.setSelectionRange(0, 99999)
        document.execCommand("copy")
        toast.success(`Hi! Now you can: ctrl+v: ${copyText.value} `)
      }
    
      return (
        <>
          
          
                    E-mail
                  
                  
          
        
      )
    }
    

提交回复
热议问题