Saturday

How to copy given text to the clipboard in react with typescript


import React from 'react';
import { LightTooltip } from '../tooltip/lightTooltip';

interface IOwnProps {
  messageToBeCopied: string | null;
}

export default class CopyToClipboard extends React.Component<IOwnProps> {

  render() {
    const { messageToBeCopied, children } = this.props;
    let isCopySuccess = false;

    if (messageToBeCopied) {
      try {
        const textField = document.createElement('textarea');
        textField.innerText = messageToBeCopied;
        document.body.appendChild(textField);
        textField.select();

        isCopySuccess = document.execCommand('copy');
        textField.remove();

      } catch (e) {
        isCopySuccess = false;
      }

      return (
        <LightTooltip
          leaveDelay={1}
          leaveTouchDelay={1}
          title={isCopySuccess === false ? 'Failed to copy.' : 'Copied.'}
        >
          {children as React.ReactElement}
        </LightTooltip>
      );
    }

    return <>{children}</>;
  }
}

import { withStyles, Theme } from '@material-ui/core/styles';
import Tooltip from '@material-ui/core/Tooltip';

export  const LightTooltip = withStyles((theme: Theme) => ({
  tooltip: {
    backgroundColor: theme.palette.common.white,
    color: 'rgba(0, 0, 0, 0.87)',
    boxShadow: theme.shadows[1],
    fontSize: 12,
    fontFamily: 'Rubik-Regular',
  },
}))(Tooltip);

import React from 'react';
import CopyToClipboard from '../copyToClipboard/copyToClipboard';

interface IState {
  clipboardMessage: string | null;
}

class Example extends React.Component<null, IState> {
  constructor(props) {
    super(props);
    this.state = {
      clipboardMessage: null,
    };
  }

  setClipboardMessage() {
    const message = 'Message for copy to clipboard';

    this.setState({
      clipboardMessage: message,
    });
  }

  render() {
    return (
      <CopyToClipboard messageToBeCopied={this.state.clipboardMessage}>
        <a onClick={() => this.setClipboardMessage()}>Copy</a>
      </CopyToClipboard>
    );
  }
}

export default Example;
Example screenshot after clicking the text:

No comments:

Post a Comment