Reputation: 23
I have something like this in a div
<div className="generated-voucher-code-details">
<p>Your voucher Code is <span style={{color:'#000000', fontWeight:'500'}}>“X1X1X1“</span>.</p>
<p>To know more on how to redeem the gift card visit the link <span style={{color:'#C7417B'}}>stores.com</span></p>
<p>Choose Preferred date, Time, Number of People and Book Now.</p>
<p>Apply voucher code in Have a Xoxo Voucher Check Box.</p>
<p>Pay Extra Amount if any through other mode of payments.</p>
<p>Your order is successfully placed.</p>
<p>You will receive confirmation within 24 hours.</p>
</div>
This Div is in a box assume, below this box, I have a button.
Now, How to copy the whole text when we click on this button?
Upvotes: 0
Views: 636
Reputation: 143
You can use document.execCommand("copy")
to implement it.
For more details head to this link.
Upvotes: 0
Reputation: 2244
welcome to stack overflow.
Please check below a working code sample.
import React, { useRef } from 'react';
export default function () {
const divRef = useRef();
const copyToCB = () => {
const div = document.createRange();
div.setStartBefore(divRef.current);
div.setEndAfter(divRef.current);
window.getSelection().empty();
window.getSelection().addRange(div);
document.execCommand('copy')
}
return (
<>
<div className="generated-voucher-code-details" ref={divRef}>
<p>Your voucher Code is <span style={{ color: '#000000', fontWeight: '500' }}>“X1X1X1“</span>.</p>
<p>To know more on how to redeem the gift card visit the link <span style={{ color: '#C7417B' }}>stores.com</span></p>
<p>Choose Preferred date, Time, Number of People and Book Now.</p>
<p>Apply voucher code in Have a Xoxo Voucher Check Box.</p>
<p>Pay Extra Amount if any through other mode of payments.</p>
<p>Your order is successfully placed.</p>
<p>You will receive confirmation within 24 hours.</p>
</div>
<button onClick={copyToCB}>Copy to CB</button>
</>
)
}
Thanks to https://www.sitepoint.com/community/t/how-to-select-text-between-div-tag-using-js/4283/5
Upvotes: 1