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.
CodePudding user response:
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>
)
}
CodePudding user response:
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