Next.js Discord

Discord Forum

Matching current location with a slug with string

Unanswered
Blue-throated Hummingbird posted this in #help-forum
Open in Discord
Blue-throated HummingbirdOP
Is there anyway I could write an if statement to check if the current path matches a string with a slug?

Something like in the image but actually works

3 Replies

@Blue-throated Hummingbird Is there anyway I could write an if statement to check if the current path matches a string with a slug? Something like in the image but actually works
based on the implementation of useSelectedLayoutSegment (https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/navigation.ts#L217) i wrote this which works for a few test cases that i have checked, do check if it works for you

"use client";

import { FlightRouterState, Segment } from "next/dist/server/app-render/types";
import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context";
import { useContext } from "react";

function getSegmentValue(segment: Segment): string {
  if (!Array.isArray(segment)) return segment;
  const [name, _, type] = segment;
  switch (type) {
    case "c":
      return `[...${name}]`;
    case "oc":
      return `[[...${name}]]`;
    case "d":
      return `[${name}]`;
  }
}

function getSelectedLayoutSegmentUnresolvedPath(
  tree: FlightRouterState,
  parallelRouteKey: string,
  first = true,
  segmentPath: string[] = []
): string[] {
  let node: FlightRouterState;
  if (first) {
    // Use the provided parallel route key on the first parallel route
    node = tree[1][parallelRouteKey];
  } else {
    // After first parallel route prefer children, if there's no children pick the first parallel route.
    const parallelRoutes = tree[1];
    node = parallelRoutes.children ?? Object.values(parallelRoutes)[0];
  }

  if (!node) return segmentPath;
  const segment = node[0];

  const segmentValue = getSegmentValue(segment);
  if (!segmentValue || segmentValue.startsWith("__PAGE__")) return segmentPath;

  segmentPath.push(segmentValue);

  return getSelectedLayoutSegmentUnresolvedPath(
    node,
    parallelRouteKey,
    false,
    segmentPath
  );
}

function useUnresolvedPathname(parallelRouteKey = "children") {
  const { tree } = useContext(LayoutRouterContext);
  return `/${getSelectedLayoutSegmentUnresolvedPath(
    tree,
    parallelRouteKey
  ).join("/")}`;
}

export default function Test() {
  const unresolvedPathname = useUnresolvedPathname();
  return <pre>{JSON.stringify(unresolvedPathname)}</pre>;
}
just curious though what use case does this have?
because if it's common enough i'm thinking of making a PR where this code will actually be validated by team members to see if it has any bugs or similar