2

I wish to automatically select some text in a span element so the user can easily copy it.

I have tried using .select() however, this appears to only work for <input> & <textarea> elements; my text is within a <span> and I don't want to change it because I handle all text within my application with another component that takes care of the styling (to answer @dandavis because comment wasn't working for me).

My text is rendered in a popup so I want to show selected for the user.

Here is what I tried:

import React from "react";
const PropTypes = React.PropTypes;

class CopyText extends React.Component {
    constructor(props) {
        super(props);
        this.handleRef = this.handleRef.bind(this);
    }

    componentDidUpdate() {
        this.copyText.select();
    }

    handleRef(component) {
        this.copyText = component;
    }

    render() {
        return (
            <span ref={this.handleRef}>
                {this.props.text}
            </span>
        );
    }
}

CopyText.propTypes = {
    text: PropTypes.string
};

export default CopyText;

Would anyone be able to help me create a custom auto-select text function for a span element? Thanks very much for your advice.

mysterious-bob
  • 105
  • 2
  • 10
  • 1
    why don't you want to use an ``? doing it hacky will make it non-accessible, and it will be complicated to make it fully cross-browser without an input. – dandavis Mar 26 '16 at 04:14
  • Use clipboard.js and define your data in the data-clipboard-text attribute. https://clipboardjs.com/ – Cesar William Alvarenga Mar 26 '16 at 04:17
  • I believe you should be able to do something similar if you look at this answer http://stackoverflow.com/a/33547949/2085190 – Kenneth Truong Mar 26 '16 at 07:45
  • @dandavis I took your advice and used an `` as I was having trouble with all browser support with @ktruong method. Thank you both. – mysterious-bob Apr 04 '16 at 11:19

1 Answers1

2

You can try this

<span ref={textAreaRef}>your text</span>
<Button type="button" onClick={() => copyEmail()}>copy</Button>

and copy function should be like this :

const copyEmail = () => {
    let currentNode = textAreaRef.current;
    if (document.body.createTextRange) {
        const range = document.body.createTextRange();
        range.moveToElementText(currentNode);
        range.select();
        document.execCommand('copy');
        range.remove();
    } else if (window.getSelection) {
        const selection = window.getSelection();
        const range = document.createRange();
        range.selectNodeContents(currentNode);
        selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('copy');
        selection.removeAllRanges();
    } else {
        alert("Could not select text, Unsupported browser");
    }
}

this will work I have used useRef to create a ref

const textAreaRef = useRef(null);
Hrishi
  • 1,210
  • 1
  • 13
  • 25