0

I use userouter to get the url of the current page and use the clipboard to copy, but the copied content is object object I expect it return an url.What problem in my code

import CopyToClipboard from "react-copy-to-clipboard";
import React,{ useState } from "react";
import { useRouter } from "next/dist/client/router";

const clip = () => {

  const {asPath} = useRouter()

    const [state, setState] = useState({
      value:{asPath},
      copied: false,
    });

    return(
        <>
     <Stack 
    position='fixed'
    bottom="0"
    css={{ backdropFilter: 'blur(10px)' }}
    w="100%"
    h="25px">

        <CopyToClipboard text={state.value}
          onCopy={() => setState({copied: true})}>
        <Box as='button' >
      <BsShare/>
        </Box>
        </CopyToClipboard>
    </Stack>
    </>
  );
};

export default clip
  • You're setting `value` as an object when you do `value: { asPath }`. Did you mean to do `value: asPath` instead? That will properly return the current path's string when accessing `state.value`. – juliomalves Nov 27 '21 at 15:00

2 Answers2

0

useRouter returns router object.

On browser side you are able to just query location.href to get current full URL.

If you are on server side, you will have to take various parts and build link yourself. You will need protocol and host (not in router object), then from router object you can get basePath, asPath (path with query, but without basePath or locale). It is better to consult documentation for version of Next that you use to see what properties you can access on router object.

Mr. Hedgehog
  • 2,644
  • 1
  • 14
  • 18
0

You don't need to use useRouter(). In Next JS, you're writing React, that's why you can implement it the way it is done in pure JavaScript:

const copyToClipboard = e => {
  navigator.clipboard.writeText(window.location.toString())
}

You can then go to your button and call the method:

<button copyToClipboard={currentLink}>
   Copy
</button>

Or you can just call the method with React's onClick():

<button onClick={copyToClipboard}>
   Click to copy current url to clipboard
</button>

You can get a lot of other suggestions with this answer: In reactJS, how to copy text to clipboard?.

Happy coding...