Search code examples
javascriptreactjsfrontendclipboardexeccommand

In React, how can I add a copy-to-clipboard functionality, by writing a simple function without any files imported?


I don't want import any files like react-copy-to-clipboard. I just want to use a simple JavaScript function, and it should work for strings, values, states, props, etc.


Solution

  • In general, we can do this in multiple ways, by importing files, which I would not recommend, because we import files only for bigger things.

    The solution in general is given for a textarea or input type.

    Here is my solution which works for props, values, strings, states, or any other data type

    clipboardCopy() {
        var copyCode = document.createElement('textarea')
        copyCode.innerText = this.props.voucher_id //you can use props,states,values,strings. I just used props 
        document.body.appendChild(copyCode)
        copyCode.select()
        document.execCommand('copy')
        copyCode.remove()
        this.toggleRegisterModal()
    }
    

    You can use this solution in React, JavaScript, or in any other framework.