{

How to copy text to clipboard in React example


This tutorial covers copy text to clipboard using below two methods

  • navigator.clipboard
  • react-copy-to-clipboard npm

navigator object in javascript provides browser capabilities, It has a clipboard API interface for accessing System clipboard, It provides cut, copies, and pastes functionalities of the native operating system. However, a clipboard is a short content buffer that exists across multiple pages or requests.

Copy text to clipboard using navigator

System clipboard in react can be accessed using Navigator.clipboard API. writeText method provides writing content to the clipboard.

Navigator support all major browsers.

In this example,

  • There is a textbox and button on a page and button click copy the text to the clipboard
  • user enters the text into the textbox, event handler onChange fires, and stores this into react state.
  • On clicking button, onClick event fires, and its event handler executes
  • Inside handler, Copy textbox value into clipboard using writeText method
import React, { Component } from 'react';

class CopyToClipboard extends Component {
    constructor(props) {
        super(props);

        this.state = {
            result: "",
            name: ""
        }
        // this.updateInput = this.updateInput.bind(this);
        // this.handleSubmit = this.handleSubmit.bind(this);

    }

    handleChange = (event) => {
        this.setState({ name: event.target.value })
    }
    handleSubmit(event) {
        console.log('kiran', event.target.value)
        try {
            navigator.clipboard.writeText(event.target.value);
            this.setState({
                result: "Copied To clipboard"
            });

        } catch (err) {
            this.setState({
                result: "Copy Failed"
            });
        }
    }


    render() {
        return (
            <div>
                <input type="text" onChange={this.updateInput} />

                <button onClick={this.handleSubmit}>Copy text</button>
                <div>
                    status : {this.state.result}
                </div>
               
            </div>
        );
    }
}

export default CopyToClipboard;

The same functionality can be achieved with the popular react-copy-to-clipboard npm library

react-copy-to-clipboard example

First, Install the react-copy-to-clipboard library to the existing react application with the below npm command.

npm install --save react react-copy-to-clipboard

CopyToClipboard is a wrapper or container for a button that contains text attribute with content and result callback with onCopy attribute. It has a button as a child element.

Call back events functions to bind the typed text.

Complete example:

import React, { Component } from 'react';

class CopyToClipboard extends Component {
    constructor(props) {
        super(props);

        this.state = {
            result: "",
            name: ""
        }
    

    }

    handleChange = (event) => {
        this.setState({ name: event.target.value })
    }

    copyStatus() {
        this.setState({
            result: "Copied"
        });
    }


    render() {
        return (
            <div>
                <input type="text" onChange={this.updateInput} />

                <CopyToClipboard text={this.state.name} onCopy={this.copyStatus}>
                    <button>Copy</button>
                </CopyToClipboard>
                <div>
                    status : {this.state.result}
                </div>

            </div>
        );
    }
}

export default CopyToClipboard;
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

ReactJS Append variables with strings, jsx state and prop concatenate html

How to display the content of a JSON file in React with example

Reactjs Fix Must call a super constructor in derived class before accessing this

How to change default port in React with create-react-app command?

How to create an react typescript application | Create-react-app typescript application

How to handle broken images in React | fallback for broken images

Fixing an error You are running create-react-app 4.0.3, which is behind the latest release (5.0.0) in React