We want to render current sitecore item url in one of the sitecore nextjs component.
Just want to know if there is any API or any other correct way to do it?
You can use useSitecoreContext hook to read the item path(relative URL) in NextJS project.
import { useSitecoreContext } from '@sitecore-jss/sitecore-jss-nextjs';
const { sitecoreContext } = useSitecoreContext();
const relativeUrl = sitecoreContext?.itemPath as string;
console.log(relativeUrl);
Similarly you can also get language using sitecoreContext.language.
You can also retrieve the hostname through below code.
import { siteResolver } from 'lib/site-resolver';
var siteName = sitecoreContext?.site?.name as string;
var hostName = siteResolver.getByName(siteName).hostName;
Hope this helps!!! Let me know in case you face any issues.
Using the useSitecoreContext you can get current sitecore item url in the sitecore nextjs component.
import { useSitecoreContext } from '@sitecore-jss/sitecore-jss-nextjs';
const CurrentItemUrl = () => {
const { route } = useSitecoreContext();
const currentUrl = route ? route.url : '';
return <div>Current Item URL: {currentUrl}</div>;
};
export default CurrentItemUrl;
Hope this help!!
You can write the below code in the Layout.tsx file:
const currentUrl = typeof window !== 'undefined' ? window.location.href : '';