0

I have a component that I need to get the current full URL in, here's the simplied version:

/**
 * Share dropdown component
 */
export const ShareDropdown: React.FC<{ className: string }> = ({
  className,
}) => {
  return (
    <div className={className}>{currentURL}</div>
  )
}

Did some Googling and saw some say use Next's router (but didn't see that return the domain), other using getInitialProps but didn't see how to incorporate into a functional component.

New to all of this, so just trying to find the best way, seems like it should be simple.

2

2 Answers 2

1

You can use simply useRouter from nextjs just like this

import { useRouter } from 'next/router';
...
const { asPath } = useRouter();
...
return (
   <div className={className}>http://example.com{asPath}</div>
)

Additionally you can save http://example.com in your environment variables

If you have configured a base path you need to get it

 import { useRouter, basePath } from 'next/router';
 

More info about useRouter here

Sign up to request clarification or add additional context in comments.

Comments

0

Store window.location.href as a variable. so, like: const URL = window.location.href and then simply put {URL} here:

/**
 * Share dropdown component
 */
export const ShareDropdown: React.FC<{ className: string }> = ({
  className,
}) => {
const URL = window.location.href
  return (
    <div className={className}>{URL}</div>
  )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.