In reactJS, how to copy text to clipboard?

前端 未结 21 1869
刺人心
刺人心 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条回答
  • This work for me:

    const handleCopyLink = useCallback(() => {
        const textField = document.createElement('textarea')
        textField.innerText = url
        document.body.appendChild(textField)
        if (window.navigator.platform === 'iPhone') {
          textField.setSelectionRange(0, 99999)
        } else {
          textField.select()
        }
        document.execCommand('copy')
        textField.remove()
        
        toast.success('Link successfully copied')
      }, [url])
    
    0 讨论(0)
  • 2020-12-02 05:14

    Use this simple inline onClick function on a button if you want to programatically write data to the clipboard.

    onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}}
    
    0 讨论(0)
  • 2020-12-02 05:15

    Why do not use just event clipboardData collection method e.clipboardData.setData(type, content)?

    In my opinion is the most streightforward method to achieve pushing smth inside clipboard, check this out (i've used that to modify data while native copying action):

    ...
    
    handleCopy = (e) => {
        e.preventDefault();
        e.clipboardData.setData('text/plain', 'Hello, world!');
    }
    
    render = () =>
        <Component
            onCopy={this.handleCopy}
        />
    

    I followed that path: https://developer.mozilla.org/en-US/docs/Web/Events/copy

    Cheers!

    EDIT: For testing purposes, i've added codepen: https://codepen.io/dprzygodzki/pen/ZaJMKb

    0 讨论(0)
  • 2020-12-02 05:15

    navigator.clipboard doesn't work over http connection according to their document. So you can check if it's coming undefined and use document.execCommand('copy') instead, this solution should cover almost all the browsers

    const defaultCopySuccessMessage = 'ID copied!'
    
    const CopyItem = (props) => {
      const { copySuccessMessage = defaultCopySuccessMessage, value } = props
    
      const [showCopySuccess, setCopySuccess] = useState(false)
    
    
      function fallbackToCopy(text) {
        if (window.clipboardData && window.clipboardData.setData) {
          // IE specific code path to prevent textarea being shown while dialog is visible.
          return window.clipboardData.setData('Text', text)
        } else if (document.queryCommandSupported && document.queryCommandSupported('copy')) {
          const textarea = document.createElement('textarea')
          textarea.innerText = text
          // const parentElement=document.querySelector(".up-CopyItem-copy-button")
          const parentElement = document.getElementById('copy')
          if (!parentElement) {
            return
          }
          parentElement.appendChild(textarea)
          textarea.style.position = 'fixed' // Prevent scrolling to bottom of page in MS Edge.
          textarea.select()
          try {
            setCopySuccess(true)
            document.execCommand('copy') // Security exception may be thrown by some browsers.
          } catch (ex) {
            console.log('Copy to clipboard failed.', ex)
            return false
          } finally {
            parentElement.removeChild(textarea)
          }
        }
      }
    
      const copyID = () => {
        if (!navigator.clipboard) {
          fallbackToCopy(value)
          return
        }
        navigator.clipboard.writeText(value)
        setCopySuccess(true)
      }
    
      return showCopySuccess ? (
        <p>{copySuccessMessage}</p>
      ) : (
        <span id="copy">
          <button onClick={copyID}>Copy Item </button>
        </span>
      )
    }
    

    And you can just call and reuse the component anywhere you'd like to

    const Sample=()=>(
       <CopyItem value="item-to-copy"/>
    )
    
    0 讨论(0)
  • 2020-12-02 05:21
     copyclip = (item) => {
        var textField = document.createElement('textarea')
        textField.innerText = item
        document.body.appendChild(textField)
        textField.select()
        document.execCommand('copy')
        this.setState({'copy':"Copied"});
        textField.remove()
        setTimeout(() => {
          this.setState({'copy':""});
        }, 1000);
     }
    
     <span   className="cursor-pointer ml-1" onClick={()=> this.copyclip(passTextFromHere)} >Copy</span> <small>{this.state.copy}</small>
    
    0 讨论(0)
  • 2020-12-02 05:22

    Why use you need an npm package when you can get all within a single button like this

    <button 
      onClick={() =>  navigator.clipboard.writeText('Copy this text to clipboard')}
    >
      Copy
    </button>
    

    I hope this helps @jerryurenaa

    0 讨论(0)
提交回复
热议问题