DEV Community

Aman Pareek
Aman Pareek

Posted on

Copy to clipboard URL in Next JS

First import useRouter and useState.

import { useRouter } from "next/router";
import { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

In function

const share = useRouter();
    const base = "http://localhost:3000";

    const links = base + share.asPath;
    const copylink = (e) => {
        navigator.clipboard.writeText(links)
    }
Enter fullscreen mode Exit fullscreen mode

In Html

<div onClick={copylink} className="shareicon" >
    <p> Copy to CLipboar </p>
</div>
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
fabriciodeveloper profile image
Fabrício Santos

Easy and right on time, tks

Collapse
 
yousuf4you profile image
Yousuf Ahamad

Are you sure, it works in nextjs 13+ app routing??

Collapse
 
amanp30 profile image
Aman Pareek

I'm not sure of v13