Enabling clipboard copy in React

Working with the clipboard in a webapp is more complicated than it needs to be due to differences in browsers and security concerns about copied content being retrievable by multiple users of the same browser. For my Ephemeral Exchange console app, I wanted to enable copying links from the tutorial section. Luckily, I'm using React - and there's  nice React component for doing that. 

The joy of re-usable components. 

I wanted to add this retrospectively to many pages, but because every is built with reusable components it was a breeze to do. First step was to create a wrapper component for react-copy-to-clipboard that would treat all presentation in the same way. 

This takes a content property, displays an colorizes it, adds an icon and a tooltip
//XClipboard component
import React from "react";
import CopyToClipboard from 'react-copy-to-clipboard';
import IconButton from 'material-ui/IconButton';
import FontIcon from 'material-ui/FontIcon';
import {indigo500} from 'material-ui/styles/colors';
export default class  extends React.Component {
  render() {
    // what to display
    const content = this.props.content;
    const noContent = content || this.props.noContent || "";
    return  content ? 
        <span style={{color:indigo500}}>{content}</span>
        <CopyToClipboard text={content}>
          <IconButton tooltip="copy"><FontIcon className="material-icons">content_copy</FontIcon></IconButton>
      </span> : 

and lets me turn any content into a copiable link, as in the example below

I use it like this
<XClipboard content={url} noContent={"not available"} />

Retrospectively adding it to all pages

Luckily, all the places I wanted to add this were already themselves contained in components too, so I only had to make one change in that component and all pages were updated.

Source code

The code for all Ephemeral Exchange material can be found in this consolidated repository

For more like this, see React, redux, redis, material-UI and firebase. Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.