Build a CopyToClipboardButton with MUI and React
A simple sharing button that copies the current URL into the user's clipboard.
Dependencies
For the purpose of this example, all you need is React and Material UI — more specifically, the Button and Snackbar components.
Component
In the component below, I used the bare minimum to make it work.
import { Button } from '@mui/material'
const CopyToClipboardButton = () => {
const handleClick = () => navigator.clipboard.writeText(window.location)
return <Button onClick={handleClick}>Share</Button>
}
export default CopyToClipboardButton
But notice that, when the user clicks, there will be no visual feedback. Even though the URL has actually been copied to the clipboard, there's no way the user can know that it actually worked.
So let's improve this interaction. For that, we'll use the Snackbar from Material UI, which works just like a toast notification.
import { Button, Snackbar } from '@mui/material'
import { useState } from 'react'
const CopyToClipboardButton = () => {
const [open, setOpen] = useState(false)
const handleClick = () => {
setOpen(true)
navigator.clipboard.writeText(window.location.toString()))
}
return (
<>…