In this post we will review a full working implementation of a "copy to clipboard" in react. This includes the javascript code to handle the copy, the react code to handle the show/hide of the "text copied" message upon 2 seconds timeout, and a css styling for the message on top.
We start with the react & redux template:
npx create-react-app my-app --template redux
Now update the application file to hold the following:
App.js
import React, {useState} from 'react'
import './App.css'
function App() {
const [show, setShow] = useState(false)
const text = 'this is my text, click on the copy icon to copy it.'
function click() {
navigator.clipboard.writeText(text).then(() => {
setShow(true)
setTimeout(() => {
setShow(false)
}, 2000)
})
}
let copiedMessage = null
if (show) {
copiedMessage = (
<div
className="copy-message"
>
Copied to clipboard
</div>
)
}
return (
<div className="root">
<div className="header">Right below, we have the example.</div>
<div className="container">
<div className="copy-icon" onClick={click}>{copiedMessage}</div>
<div className="text">{text}</div>
</div>
<div className="header">The end of the example.</div>
</div>
)
}
export default App
The application includes an optional div which contains the "copied to clipboard" message. This div is displayed for 2 seconds after clicking the copy to clipboard icon. To implement this, we use react's useState function.
The actual copy of the text is done using the navigator.clipboard. In case of need of old browsers backward compatibility, use different methods, and described here.
We include the stylesheet to hold the following:
App.css
.root{
font-size: 30px;
}
.container {
display: flex;
flex-direction: row;
}
.copy-icon {
background: url('copy.png') center;
background-size: cover;
margin: 5px;
height: 25px;
width: 25px;
padding: 0;
z-index: 99;
cursor: pointer;
}
.header{
margin: 30px;
}
.copy-message {
font-size: 25px;
float: left;
border: 1px solid black;
background: white;
width: 250px;
height: 30px;
margin-left: 20px;
margin-top: 20px;
}
We use flex to display the icon and the text side by side.
To ensure the "copied to clipboard" message is on top, we use both z-index and floating mode.
No comments:
Post a Comment