Search code examples
javascriptreactjsexeccommand

document.execCommand ('copy') don't work in React


I have the function below that is called on click of a button . Everything works well, but the document.execCommand ('copy') simply does not work.

If I create another button and call only the contents of if in a separate function, it works well.

I have already tried calling a second function inside the first one, but it also does not work. the copy is only working if it is alone in the function.

Does anyone know what's going on?

copyNshort = () => {
    const bitly = new BitlyClient('...') // Generic Access Token bit.ly
    let txt = document.getElementById('link-result')

    bitly.shorten(txt.value)
        .then((res) => {
            this.setState({ shortedLink: res.url })

            if (this.state.shortedLink !== undefined) {
                document.getElementById('link-result-shorted').select() // get textarea value and select
                document.execCommand('copy') // copy selected
                console.log('The link has been shortened and copied to clipboard!')
                ReactDOM.render(<i className="fas fa-clipboard-check"></i>, document.getElementById('copied'))
            }
            console.log('Shortened link 👉🏼', res.url) // Shorted url
        })
}

Solution

  • The problem is that the copy-to-clipboard functionality will only work as a direct result of a user's click event listener... This event cannot be virtualised and the execCommand will not work anywhere else than the immediate callback assigned to the event listener... Because react virtualises and abstracts 'events' then that's very possibly where the problem lies and as suggested you should be using React's react-copy-to-clipboard.