Copy Current URL Button with Material UI on A Next.js Project

Tutorial
Web Development
Blog
Studiofru
Studiofru
Cover Image for Copy Current URL Button with Material UI on A Next.js Project

There is no doubt that almost every website owner wanted their website to be popular, especially through organic visitors. One of the many methods in order to make a website popular is by sharing the URL link through social media, email marketing and messenger. 

While there are many JavaScript libraries that can be use to easily implement share button on a Next.js project, one thing that not many of the libraries provide is the copy current URL button. So here in this article, we’ll dive into the way to make it. 

Material UI is one of our favourite frameworks to use as our main component design. Not only because it’s free but is also because it’s beautiful, very easy to implement, and is customizable. We are using the framework in almost all of our web projects and are so happy with the result.

Our copy current URL button is created by using tooltip, icon button, Material UI icons and a bit of styling. It is a single component that we combine with the social share buttons. To see it live, please check the buttons on the ‘Share this article’ section on this post. 

Here’s the code to the copy current URL button that we are talking about:

import React, { useState } from "react";
import IconButton from '@mui/material/IconButton';
import Tooltip, { tooltipClasses } from '@mui/material/Tooltip';
import { styled } from '@mui/material/styles';

import ContentCopyIcon from '@mui/icons-material/ContentCopy';

const LightTooltip = styled(({ className, ...props }) => (
  <Tooltip {...props} classes={{ popper: className }} />
))(({ theme }) => ({
  [`& .${tooltipClasses.tooltip}`]: {
    backgroundColor: theme.palette.common.white,
    color: 'rgba(0, 0, 0, 0.87)',
    boxShadow: theme.shadows[1],
    fontSize: 11,
  },
}));

export default function CopyURLButton () {
    const [copied, setCopied] = useState(false);

    const [anchorEl, setAnchorEl] = React.useState(null);
    const open = Boolean(anchorEl);
    const handleClick = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
    setAnchorEl(null);
    };


function copy() {
    const el = document.createElement("input");
    el.value = window.location.href;
    document.body.appendChild(el);
    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);
    setCopied(true);
  }

    return (
         <LightTooltip title={!copied ? "Copy link" : "Copied!"}>
            <IconButton><ContentCopyIcon color="primary" size="small" onClick={copy} /></IconButton>
         </LightTooltip>
    )
}   
 

External Link
Click here

Share this article