Found best way to do it. i mean the fastest way: w3school
https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
Inside a react functional component. Create a function named handleCopy:
function handleCopy() {
// get the input Element ID. Save the reference into copyText
var copyText = document.getElementById("mail")
// select() will select all data from this input field filled
copyText.select()
copyText.setSelectionRange(0, 99999)
// execCommand() works just fine except IE 8. as w3schools mention
document.execCommand("copy")
// alert the copied value from text input
alert(`Email copied: ${copyText.value} `)
}
<>
<input
readOnly
type="text"
value="[email protected]"
id="mail"
/>
<button onClick={handleCopy}>Copy email</button>
</>
If not using React, w3schools also have one cool way to do this with tooltip included: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_copy_clipboard2
If using React, a cool think to do: Use a Toastify to alert the message.
https://github.com/fkhadra/react-toastify This is the lib very easy to use.
After installation, you may be able to change this line:
alert(`Email copied: ${copyText.value} `)
For something like:
toast.success(`Email Copied: ${copyText.value} `)
If you want to use it, dont forget to Install toastify. import ToastContainer and also toasts css:
import { ToastContainer, toast } from "react-toastify"
import "react-toastify/dist/ReactToastify.css"
and add the toast container inside return.
import React from "react"
import { ToastContainer, toast } from "react-toastify"
import "react-toastify/dist/ReactToastify.css"
export default function Exemple() {
function handleCopy() {
var copyText = document.getElementById("mail")
copyText.select()
copyText.setSelectionRange(0, 99999)
document.execCommand("copy")
toast.success(`Hi! Now you can: ctrl+v: ${copyText.value} `)
}
return (
<>
<ToastContainer />
<Container>
<span>E-mail</span>
<input
readOnly
type="text"
value="[email protected]"
id="mail"
/>
<button onClick={handleCopy}>Copy Email</button>
</Container>
</>
)
}