GithubHelp home page GithubHelp logo

react-copy-to-clipboard's Introduction

react-copy-to-clipboard npm

Gitter

CircleCI Dependencies Dev Dependencies

Copy to clipboard React component

Based on copy-to-clipboard

Would try to use execCommand with fallback to IE specific clipboardData interface and finally, fallback to simple prompt with proper text content & 'Copy to clipboard: Ctrl+C, Enter'

Copy to clipboard

Installation

NPM

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

Don't forget to manually install peer dependencies (react) if you use npm@3.

1998 Script Tag:

<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-copy-to-clipboard/build/react-copy-to-clipboard.js"></script>
(Module exposed as `CopyToClipboard`)

Live design system demo

https://www.jinno.io/app/18/

Simple web demo

http://nkbt.github.io/react-copy-to-clipboard

Codepen demo

http://codepen.io/nkbt/pen/eNPoQv

Usage

import React from 'react';
import ReactDOM from 'react-dom';
import {CopyToClipboard} from 'react-copy-to-clipboard';

class App extends React.Component {
  state = {
    value: '',
    copied: false,
  };

  render() {
    return (
      <div>
        <input value={this.state.value}
          onChange={({target: {value}}) => this.setState({value, copied: false})} />

        <CopyToClipboard text={this.state.value}
          onCopy={() => this.setState({copied: true})}>
          <span>Copy to clipboard with span</span>
        </CopyToClipboard>

        <CopyToClipboard text={this.state.value}
          onCopy={() => this.setState({copied: true})}>
          <button>Copy to clipboard with button</button>
        </CopyToClipboard>

        {this.state.copied ? <span style={{color: 'red'}}>Copied.</span> : null}
      </div>
    );
  }
}

const appRoot = document.createElement('div');
document.body.appendChild(appRoot);
ReactDOM.render(<App />, appRoot);

Options

text: PropTypes.string.isRequired

Text to be copied to clipboard

onCopy: PropTypes.func

Optional callback, will be called when text is copied

onCopy(text, result)

result (bool): Returns true if copied successfully, else false.

options: PropTypes.shape({debug: bool, message: string})

Optional copy-to-clipboard options.

See API docs for details

children: PropTypes.node.isRequired

CopyToClipboard is a simple wrapping component, it does not render any tags, so it requires the only child element to be present, which will be used to capture clicks.

<CopyToClipboard text="Hello!">
  <button>Copy to clipboard</button>
</CopyToClipboard>

Development and testing

Currently is being developed and tested with the latest stable Node 8 on OSX.

To run example covering all CopyToClipboard features, use yarn start, which will compile example/Example.js

git clone [email protected]:nkbt/react-copy-to-clipboard.git
cd react-copy-to-clipboard
yarn install
yarn start

# then
open http://localhost:8080

Tests

# to run ESLint check
yarn lint

# to run tests
yarn test

# to run end-to-end tests
# first, run `selenium/standalone-firefox:3.4.0` docker image
docker run -p 4444:4444 selenium/standalone-firefox:3.4.0
# then run test
yarn e2e

License

MIT

react-copy-to-clipboard's People

Contributors

amazingturtle avatar arnabsen avatar bertho-zero avatar butenkot avatar cesarandreu avatar dantman avatar dilatorily avatar forresst avatar greenkeeperio-bot avatar hozefaj avatar lama-pacos avatar lsanwick avatar moroshko avatar morzloof avatar nkbt avatar npmcdn-to-unpkg-bot avatar pegase745 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-copy-to-clipboard's Issues

Tab Delimited Values copied through this component not pasting into Excel properly.

Hi! Thanks for building this, it's served my team well in one particular instance.

However, just want to draw to your attention that I've been having some difficulty making this component work with tab-delimited text, which I needed for a feature copying/pasting tabular data from my app into MS Excel. Thought I'd post my findings here in case anyone else has the same issue. (I'll post one there too)

It seems the problem is in the Copy-To-Clipboard component that this depends on. It's selecting the html span element around the text rather than just the plain text itself.

I ended up creating a new method for this particular copy to clipboard button, using the same strategy of inserting the text into the DOM then calling document.execCommand, but with a textarea rather than a span, as follows. The reason for this is because we can then use the select() method, which only works on textarea but seems to select the text more 'purely':

(apologies to all those offended by CoffeeScript)

copyToClipboard : (text) ->
    textArea = document.createElement("textarea")
    textArea.style.position = 'fixed'
    textArea.style.top = 0
    textArea.style.left = 0
    textArea.style.width = '2em'
    textArea.style.height = '2em'
    textArea.style.padding = 0
    textArea.style.border = 'none'
    textArea.style.outline = 'none'
    textArea.style.boxShadow = 'none'
    textArea.style.background = 'transparent'
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()

    try
      successful = document.execCommand 'copy'
      msg = successful ? 'successful' : 'unsuccessful'
      log 'Copying text command was ' + msg
    catch err
      alert 'Unable to copy - please contact your admin.'

    document.body.removeChild textArea

Update to latest node engine

When I run yarn add react-copy-to-clipboard I'm getting error [email protected]: The engine "node" is incompatible with this module. Expected version ">=4 <=9".

I think it's time have have this arranged. I'm using Node 10

Always given "copy to clipboard" prompt

Latest version of react-copy-to-clipboard (4.1.0)

OSX Chrome Version 49.0.2623.112 (64-bit)
and
OSX Chrome Version 52.0.2705.0 canary (64-bit)

Used inside a React 15 component, imported with
import CopyToClipboard from 'react-copy-to-clipboard'

Used like so:

<CopyToClipboard text={window.location.href}
        onCopy={() => this.setState({ copied: true })}>
            <div className='photo-page-permalink'>
              {window.location.href}
            </div>
</CopyToClipboard>

Always gives the "Copy to clipboard: Ctrl+C, Enter" prompt, never copies silently.

Example page (http://nkbt.github.io/react-copy-to-clipboard/example/) in same browsers copies to clipboard silently.

On closing the prompt, an error is always thrown:

Uncaught TypeError: reselectPrevious is not a function

Any ideas?

Thanks!

Browser alert when copying larger amounts of text

Using the latest version 5.0.1 of react-copy-to-clipboard, when I copy large amounts of text I get a browser popup:
screen shot 2017-10-12 at 10 35 02 am
The code is:

` const formatted = JSON.stringify(this.props.resultsState.rawResult, null, 2);

  <div>
    <CopyToClipboard text={formatted} onCopy={this.handleTextCopied}>
          <ClipboardIcon className='clipboard-icon' />
    </CopyToClipboard>`

Support for React 0.14

Looks like react-copy-to-clipboard does not support React 0.14.0-beta3 yet:

npm ERR! peerinvalid The package react does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react@^0.13.3

Any chance to add support for 0.14.0-beta3?

Display name for component is no longer correctly set.

We get a failing snapshot test on our code related to the name of the CopyToClipboard class:

 -    <CopyToClipboard
 +    <Component

You need to set the displayName on the class:

CopyToClipboard.displayName = 'CopyToClipboard';

IE scrolls down when copy

When I click to copy my IE scrolls to the end of page, though it copies and works well in another browsers.

pass the JS event onCopy()

So I want to do something on the DOM element that originated the copy.

I've tried using onClick but nothing happens. I will assume because the handler gets overwritten by the CopyToClipboard internal logic.

So I tried using 'onCopy', but only the copied text gets passed to the handler.

It would be great if the DOM element where the click was originated was passed as a second argument of onCopy or even better pass the full JS event.

Is there any logical argument against this?

@nkbt would you accept a pull request with this functionality?

Issue testing with Jest

I'm trying to test integration of this component via Jest, but the onCopy callback doesn't seem to be getting called. I'm wondering if I'm doing something wrong.

MyComponent.js

class MyComponent extends React.PureComponent {
  static propTypes = {
    label: string.isRequired,
    value: string.isRequired,
    showInfoToast: func.isRequired
  };

  render() {
    const { label, value } = this.props;

    return (
      <CopyToClipboard text={value} onCopy={this.handleCopy}>
        <Icon
          name="copy"
          role="button"
          tabIndex={0}
          aria-label={label}
        />
      </CopyToClipboard>
    );
  }

  handleCopy = () => {
    const { label, showInfoToast } = this.props;
    showInfoToast(`${label} copied to clipboard.`);
  }
};

MyComponent.test.js

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';

describe('<MyComponent />', () => {
  const mountContainer = (props = {}) => {
    return shallow(<MyComponent label="Name" value="Joe" {...props} />);
  };

  it('calls showInfoToast prop when copy icon is clicked', () => {
    const showToastSpy = jest.fn();
    const wrapper = mountContainer({ showInfoToast: showToastSpy });
    wrapper.find('Icon').simulate('click');
    expect(showToastSpy).toHaveBeenCalledWith('Name copied to clipboard.');
  });
});

Result

Expected mock function to have been called with:
  ["Name copied to clipboard."]
But it was not called.

Getting type and constructor errors

ERROR in [at-loader] ./node_modules/@types/react-copy-to-clipboard/index.d.ts:26:39
TS2314: Generic type 'Component<P, S>' requires 2 type argument(s).

ERROR in [at-loader] ./src/Models/Main/QrCodeCreator.tsx:57:26
TS2604: JSX element type 'CopyToClipboard' does not have any construct or call signatures.

Use:

import * as CopyToClipboard from 'react-copy-to-clipboard';
...
                        <CopyToClipboard text={registrationLink} } >
                            <RaisedButton label={ClientResources.qrCodeCreation.copyButton} secondary={true} />
                        </CopyToClipboard>

I'm on windows. Any ideas why this happens?

Discontiguous selection is not supported.

When I use <div> rather than <button> inside <CopyToClipboard>, I get a warning in the console, and nothing is copied to the clipboard.

<CopyToClipboard text={'hey'}>
  <div>Copy to clibpoard</div>
</CopyToClipboard>

Discontiguous selection is not supported.

Codepen

Any idea why is this happening?

Support adding onClick listener to the CopyToClipboard component

For now I have to add the onClick listener to the parent/child component:

<span onClick={stopPropagation}>
  <CopyToClipboard text="...">
    <span>copy</span>
  </CopyToClipboard>
</span>
<CopyToClipboard text="...">
  <span onClick={stopPropagation}>copy</span>
</CopyToClipboard>

Both work.

But this doesn't:

<CopyToClipboard text="..." onClick={stopPropagation}>
  <span>copy</span>
</CopyToClipboard>

What's the reason not use ES6 for creating classes?

Hi Nick, this is Robert. I've been to Sydjs too and listened your talk.

I saw you wrote quite a lot React component packages. And you are using ES6, however, what's the reason that you still use

const App = React.createClass({ });

instead of using ES6:

class App extends React.Component { }

is there any special reason or benefits for writing those in old method?

cheers

Register on Bower

Make sure it can be used via Bower. Find out how to properly publish it without checking in build artifact into master.

[help wanted] Cannot install package

Hi, I just downloaded your ``react-copy-to-clipboard`. As soon as I downloaded your package and ran my exact same build I got the following error message:

ERROR in ./~/react-dom/index.js
Module not found: Error: Cannot resolve module 'react/lib/ReactDOM' in C:\xampp\htdocs\Wizer\tools\node_modules\react-dom
 @ ./~/react-dom/index.js 3:17-46

This error still occurs even after deleting the import statement and component out of my project... Are you updating depencenies automatically or so?! Not sure why it also changed something in React :(

This was the message after installing it (from npm):

C:\xampp\htdocs\Wizer\tools>npm install --save react react-copy-to-clipboard
- [email protected] node_modules\immutable
[email protected] C:\xampp\htdocs\Wizer\tools
+-- [email protected]
| `-- [email protected]
|   +-- [email protected]
|   | `-- [email protected]
|   `-- [email protected]
+-- UNMET PEER DEPENDENCY react-addons-shallow-compare@~0.14.0 || ^15.0.0
`-- [email protected]
  `-- [email protected]
    `-- [email protected]

Also the UNMET peer depencency is fine as this was already from the beginning of my project. (2 months ago).

I just saw that it really added React as a separate dependency in my package.json ?

    "react": "^15.4.2",
    "react-copy-to-clipboard": "^4.2.3",

Getting warnings

Hi there,

Thank you for this wonderful component!

I am getting the below warnings on latest Chrome:

127:14  warning  Script URL is a form of eval  no-script-url (webpackHotDevClient.js:181)
133:14  warning  Script URL is a form of eval  no-script-url (webpackHotDevClient.js:181)
139:14  warning  Script URL is a form of eval  no-script-url (webpackHotDevClient.js:181)

OS X 10.11.6
Chrome Version 55.0.2883.95 (64-bit)

Edit: I am using

How to resolve these?

Change 'text' propType to allow functions.

This is as much a question as it is a request. I was hoping you could let me know your thoughts on allowing functions for the 'text' prop (maybe add another prop, like getText) so that the text doesn't have to be passed on every render, only when the button is clicked.

My use case for this is with Facebook's fixed-data-table, where I am providing a button to copy the table to the clipboard, which first has to get all of the data (fixed-data-table only renders the currently visible rows) and convert it to an html table structure or a csv structure.

The problem with this is, in most instances of the parent re-rendering, that adds up to a lot of wasted work re-generating the text prop every time. It would be more efficient (at least I think so) to simply pass a function which returns the text to be copied. That way, the text will only be generated when the user actually needs it. It could also open the door for Promise related stuff I guess, but that isn't really relevant here.

I'm kind of a noob, so let me know if this request is completely misguided/already possible.

Thanks.

Newlines seem to be stripped from copied text

Maybe I did something wrong, but if I try to use the component on data with newlines, I get a flat string with everything concatenated on one line in the clipboard. I reproduce this behavior on your codepen demo by just changing the "input" to be a "textarea".

Do you think it is expected behavior? Fixable? If so, how can I help?

Getting 404 on server compile - CopyToClipboard.js.map not found

I get this error in my logs:

 { [Error: Url '/public/js/CopyToClipboard.js.map' does not match any routes]
     statusCode: 404,
     message: 'Url \'/public/js/CopyToClipboard.js.map\' does not match any routes' } }

I'm using the NPM module of this and Webpack for module bundling.

CopyToClipboard: React.createClass is deprecated and will be removed in version 16

I have updated react to 15.4.2 and now have this warning :

 Warning: CopyToClipboard: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.

Will CopyToClipboard be upgrade to be compatible with version 16 of react ?

Highlighting and copying the text to be copied also copies the button text

Some of our users have been clicking the displayed text and copying. When pasted, it includes the message passed to the button. See gif below.

<div className="invite-link" style={inviteLinkStyle}>
      <div className="invite-box">
        <div className="invite-link-text">{inviteLink}stop</div>
     </div>
     div>
      <CopyToClipboard text={inviteLink}>
       <button className="btn btn-primary" onCopy={() => this.handleCopyClick()}>
            {inviteLinkMessage}
       </button>
     </CopyToClipboard>
   </div>
 </div>

https://gfycat.com/gifs/detail/OrangeEntireIrrawaddydolphin

not working in FF newest version

Hi, I use FF Version 54.0.1 where copy does not work for me (no error; just nothing happens). In chrome it works perfectly. Is there an issue when using firefox in general or should it work? Thanks for a short feedback!

children proptype is too restrictive

You should loosen the children proptype requirement since children can be an array.

eg,

<CopyToClipboard text={"some text}>
  <span>Copy to Clipboard</span>
  <i className='fa fa-clipboard' />
</CopyToClipboard>

Add another example with button and predefined value to be copied

I just implemented successfully your lib, thanks a lot. That was really easy and works like a charm so far ;)

I just wanted to share a component I created specifically, maybe it can be added to the examples on the readme?

CopyIcon.js

import React, { PropTypes, Component } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';

import Icon from './Icon';

const CopyIcon = ({ value, onCopy, ...props }) => (
  <CopyToClipboard
    text={value}
    onCopy={onCopy}
  >
    <Icon name="copy" {...props} />
  </CopyToClipboard>
);

CopyIcon.propTypes = {
  value: PropTypes.any.isRequired,
  onCopy: PropTypes.func.isRequired,
};

export default CopyIcon;

Usage:

import { toastr } from 'react-redux-toastr';

// ...

<CopyIcon
  value={'value to be copied'}
  style={{ float: 'right' }}
  onCopy={(v) => toastr.success(
    'Success',
    `${v}" copied to clipboard!`
  )}
/>

Hope it helps some!

The behavior that Selection.addRange() merges existing Range

Hi. Using the latest version of react-copy-to-clipboard, I have an issue:

My code:

const CopyContainer = ({ address, children, ...otherProps }) => (
  <CopyToClipboard text={address}>
    <a className="account" data-tip="Copy address">
      <input autoFocus type="hidden" />
      {children}
      <ReactTooltip
        effect="solid"
        event="mouseover"
        eventOff="mouseout click"
        place="bottom"
      />
    </a>
  </CopyToClipboard>
);

It's <a> tag with a tooltip on hover. On click, I have the following message, and the text is not copied.

index.js:41 [Deprecation] The behavior that Selection.addRange() merges existing Range and the specified Range was removed. See https://www.chromestatus.com/features/6680566019653632 for more details.

If I click another time, then no warning, and the text is copied.

Unable to use \r \n

My copy needs to respect new lines and returns. Is there support for this?

Does not copy empty string to clipboard

When value of the text prop is an empty string (i.e. ""), the result parameter inside onCopy is true, but the empty string is not copied to the clipboard. Instead, the clipboard retains whatever was already on it.

Demo: https://codepen.io/anon/pen/VyvgOr

  • This demo is a fork of the demo linked in README.md. The only difference is that state.value has been initialized to an empty string (i.e. "") instead of to "some\ntext". To reproduce the issue, you can manually pre-load your clipboard with a non-empty string (e.g. "abc") and then click on the "Copy to clipboard with button" button in the demo. Although the demo will show the red "Copied" message (suggesting, to me, that the empty string has been copied to the clipboard), the clipboard will continue to contain the previous string (e.g. "abc") instead of the empty string.

I expected the clipboard to contain the empty string (i.e. I expected the clipboard to be empty).

Observed in:

  • Chrome Version 62.0.3202.94 (Official Build) (64-bit) running on Windows 7 64-bit

Generates a warning about using deprecated feature in React.

When running with this on the server or in browser this warning shows up:

Warning: CopyToClipboard: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.

I know you're against ES6 classes but there is another solution: use stateless components!

Looks like the culprit is Component.js and there's nothing there that couldn't be done with Stateless components.

Thoughts? PRs requests?

Keyboard accessibility?

When I press the button by tabbing to focus it and pressing Space or Enter, it doesn't seem to copy anything.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.