0

I’m trying to use clipboard.js in a React component, and it causes my devserver to start failing with the Node error: ReferenceError: Element is not defined at Object.<anonymous> (/mnt/home/me/code/board/webapp/node_modules/matches-selector/index.js:6:13)

I initialize the clipboard in componentDidMount but am still getting this error. I actually think the error may have something to do with my import, because even when I don’t actually initialize the clipboard (but include the import) I get the error. Does anyone have an idea what I might be doing wrong?

Relevant code (styling excluded):

import React, { Component } from 'react';
import Clipboard from 'clipboard';

export default class CodeSnippet extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        new Clipboard('.copyButton', {
            target: () => document.getElementById('snippet')
        });
    }

    render() {
        return (      
            <div style={styles.snippetCopy}>
                <div id="snippet" style={styles.snippet}>
                    {'this text will copy'}
                </div>
                <button
                    className={"copyButton"}
                    id="clipper"
                    data-clipboard-text='snippet'
                    style={styles.buttonStyle}
                    text={'Copy code'}>
                </button>
            </div>
        );
    }
}
user3802348
  • 2,502
  • 11
  • 36
  • 49

2 Answers2

4

You can't require clipboard.js if you're doing server side rendering. It's annoying but instead of installing via npm, they suggest including the script manually like this:

<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>

https://github.com/zenorocha/clipboard.js/issues/157

Adam Fraser
  • 6,255
  • 10
  • 42
  • 54
  • 1
    I should add that the reason you can't load the lib on the server side is because it immediately tries to access `window.Element` which obviously doesn't exist until the page is rendered in a browser. – Adam Fraser Sep 13 '16 at 13:28
3

I created a fiddle updating your code. It's a suggestion of integrating clipboardjs and React, using ref's and clipboardjs' text function.

Check here: https://jsfiddle.net/mrlew/L54ky6hj/

mrlew
  • 7,078
  • 3
  • 25
  • 28
  • Thanks for the fiddle! That is a much better integration of React. I'm still getting the Node error upon importing clipboard though. – user3802348 Jul 07 '16 at 22:26
  • I teste here in a react test project, and it worked. Try updating your packages (react, clipboard) (`npm update clipboard`) and/or reinstalling it (`npm uninstall clipboard && npm install clipboard --save`). Try the same with react. Are you using webpack? – mrlew Jul 07 '16 at 22:40
  • The "copied" message (tooltip) is missing. I'm wondering if this is a clipboard js bug if used in react – Chaoste Nov 07 '16 at 16:14