useLocation()

Use the useLocation() function to retrieve a RouteLocation object for the current location.

export interface RouteLocation {
  readonly params: RouteParams; // Record<string,string>
  readonly href: string;
  readonly pathname: string;
  readonly query: Record<string, string>;
}

The return value of useLocation() is similar to document.location, but it is safe to use on the server where there is no global location object.

Path Route Parameters

useLocation() encodes the Route Parameters as params.

Assume you have:

  • Route: https://example.com/sku/[skuId]
  • User navigates to: https://example.com/sku/1234
  • Then the skuId can be retrieved through useLocation().params.skuId.
export default component$(() => {
  const { pathname, params } = useLocation();

  return (
    <>
      <h1>SKU</h1>
      <p>pathname: {pathname}</p>
      <p>skuId: {params.skuId}</p>
    </>
  );
});

The above code would generate:

<h1>SKU</h1>
<p>pathname: /sku/1234</p>
<p>skuId: 1234</p>
Made with ❤️ by