I'm trying to copy the text in the DialogContentText tag. I had a ref in the in the tag, but I couldn't figure how to actually use the ref and copy the text onto the clipboard. What exactly do I put into the handleCopyClick function body to put the text onto the clipboard? TIA

import { React, useRef } from 'react'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import { IconButton } from '@material-ui/core'; import { FileCopyOutlined } from '@material-ui/icons'; export const ExportDialog = (props) => { const { code, openExportDialog, setOpenExportDialog } = props const codeText = useRef(null) const handleClose = () => { setOpenExportDialog(false) }; const handleCopyClick = () => { // what do I put here to copy the text onto clipboard // I tried the following and It didn't work // codeText.current.select() // document.execCommand('copy') } return ( <div> <Dialog open={openExportDialog} onClose={handleClose} > <DialogTitle>{'Exported Deck Code'}</DialogTitle> <DialogContent> <DialogContentText ref={codeText}> {`${code}`} </DialogContentText> </DialogContent> <DialogActions> <IconButton onClick={()=>{handleCopyClick()}}> <FileCopyOutlined></FileCopyOutlined> </IconButton> <Button onClick={handleClose} color="primary" autofocus> Close </Button> </DialogActions> </Dialog> </div> ); } 
1

1 Answer

You can use the module "copy-to-clipboard" to copy , its straight forward and you can copy anything.

Pass the data that you want to copy in "text"

 <CopyToClipboard text={code}> <IconButton > <FileCopyOutlined></FileCopyOutlined> </IconButton> </CopyToClipboard> 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.