user3802348 user3802348 - 2 months ago 23
React JSX Question

Errors with clipboard.js in React component?

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>
);
}
}

Answer

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