How to Get the Absolute URL on the Client Side in Remix? #9864
-
Hi everyone, I'm trying to get the absolute URL on the client side and have run into a bit of confusion. I initially expected hooks like useHref, which explicitly states, that it resolves a full url to return the full URL, but it seems to only return relative paths. To work around this, I created the following custom hook: import { useEffect, useState } from "react";
export default function usePageUrl() {
const [pageUrl, setPageUrl] = useState("");
useEffect(() => {
setPageUrl(window.location.href);
}, []);
return pageUrl;
} While this works, I'm wondering if there's a "cleaner" or more idiomatic way to achieve this in Remix without relying on useEffect. Is there an existing hook or a better approach that avoids the need for side effects? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
When you say full URL, do you mean to include the origin too? Instead of |
Beta Was this translation helpful? Give feedback.
-
You could return If you want the hash you will need it client-side too. |
Beta Was this translation helpful? Give feedback.
Client-side you should use an effect, the component render is not only client-side (it runs server-side) that's why Remix hooks only gives you the pathname, the origin can be anything (Remix and RR doesn't handle that part).
I would return the origin from a loader
Another option could be to use
window.location.href
in entry.client (this runs 100% client-side) and use a custom context to make it globally available for React, and since your components run server-side you will need the same context in entry.server where you can also …