ClickToCopy.js 1.51 KiB
Newer Older
Amaury Martiny's avatar
Amaury Martiny committed
// Copyright 2015-2018 Parity Technologies (UK) Ltd.
// This file is part of Parity.
//
// SPDX-License-Identifier: BSD-3-Clause

import React, { PureComponent } from 'react';
Amaury Martiny's avatar
Amaury Martiny committed
import { Popup } from 'semantic-ui-react';
Amaury Martiny's avatar
Amaury Martiny committed
import PropTypes from 'prop-types';
Amaury Martiny's avatar
Amaury Martiny committed
import 'semantic-ui-css/components/popup.min.css';
export class ClickToCopy extends PureComponent {
Amaury Martiny's avatar
Amaury Martiny committed
  static defaultProps = {
    label: 'Click to copy'
  };

  static propTypes = {
    children: PropTypes.node,
    label: PropTypes.string.isRequired
  };

  state = {
    copied: false
  };

  handleCopy = () => {
    // https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f
    // Note react-copy-to-clipboard created a bug, https://github.com/nkbt/react-copy-to-clipboard/issues/92
    const el = document.createElement('textarea');
    el.value = this.props.textToCopy;
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);

    this.setState({ copied: true });
  };

Amaury Martiny's avatar
Amaury Martiny committed
  handleResetCopied = () => this.setState({ copied: false });
Amaury Martiny's avatar
Amaury Martiny committed

Amaury Martiny's avatar
Amaury Martiny committed
  render () {
    const { children, label, textToCopy, ...otherProps } = this.props;
Amaury Martiny's avatar
Amaury Martiny committed
    const { copied } = this.state;

    return (
Amaury Martiny's avatar
Amaury Martiny committed
      <Popup
        content={copied ? 'Copied.' : 'Click to copy'}
        inverted
        onClose={this.handleResetCopied}
        position='bottom center'
        size='mini'
        trigger={
          <div onClick={this.handleCopy} {...otherProps}>
            {children}
          </div>
        }
      />