I have a section in which I want user to copy html to clipboard, this element should be hidden here is what I have so far
live demo : live demo
Here is code I have so far.
export default function App() {
const tableRef = useRef(null);
const textRef = useRef(null);
const [copySuccess, setCopySuccess] = useState("");
const copyToClipboard = (e) => {
let tableRange = document.createRange();
tableRange.selectNodeContents(tableRef.current);
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(tableRange);
document.execCommand("Copy");
sel.removeAllRanges();
setCopySuccess("Copied!");
};
return (
<div className="App">
<textarea
ref={textRef}
style={{ opacity: 0, position: "absolute", top: "-200px" }}
></textarea>
<div
aria-hidden="true"
ref={tableRef}
className="table"
style={{ display: "none" }}
>
<table>
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
</tbody>
</table>
</div>
{document.queryCommandSupported("copy") && (
<div>
<button onClick={copyToClipboard}>Copy</button>
{copySuccess}
</div>
)}
</div>
);
}
Expected: copy the hidden html table to clipboard
What do I need to do so that I can copy that hidden element to clipboard?
Ok, hidden element is not available directly in DOM so you can not copy it from there. They are just used to carry data from one state to another or from rendering form to back to controller. If you need that data, you can bind that in ViewBag.
const a = window.param;
window.param = ViewBag.param;
const copyToClipboard = (e) => {
ViewBag.param = e;
let tableRange = document.createRange();
tableRange.selectNodeContents(tableRef.current);
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(tableRange);
document.execCommand("Copy");
sel.removeAllRanges();
setCopySuccess("Copied!");
};
Please refer this link also. Access a viewbag property in reactjs