Potamir
Potamir

Reputation: 339

NextJS Inherit Query Param From Previous Page

I want to make the param from current url are pass to the next url when router change. for example:
My current url: localhost:3000/dashboard/?name=abc
when I move to page /profile for example then I expect the url must be like this:
Next Url: localhost:3000/profile/?name=abc

I want to pass automatically everytime we move the page even though we didn't include the param when we are pushing the router
If I do this: router.push("/profile"))
The result will be: localhost:3000/profile/?name=abc if I have query param name on the previous router
If anyone can refer me the documentation about it because I can't found it, or if you are have any solution for it. Thank You!

Upvotes: 1

Views: 2299

Answers (2)

ktt
ktt

Reputation: 31

Similar to Drew Reese's comment, I'm unaware of a better way than the following. I created a custom link component. I simply use this instead of <a> whenever I have a link where I want query params passed along. (Or you could use it implementing Next <Link>; I have reasons for using <a>.)

This is using modern Next. (Docs: "Use the <Link> component for navigation unless you have a specific requirement for using useRouter.")

You could also change it to pass along all query params without needing to know their names.

It took 15 minutes to replace all relevant links with this component, but after that's done you've got a quick modular solution for future use.

"use client";
import { useSearchParams } from "next/navigation";
import { ReactNode, useEffect, useState } from "react";

// This is for Typescript; delete if not using
interface CustomLinkProps
  extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
  href: string;
  children: ReactNode;
}

const CustomLink: React.FC<CustomLinkProps> = ({
  href,
  children,
  ...props
}) => {
  const searchParams = useSearchParams();
  const [finalHref, setFinalHref] = useState(href);

  useEffect(() => {
    const utmSource = searchParams.get("utm_source");
    const utmCampaign = searchParams.get("utm_campaign");

    if (utmSource && utmCampaign) {
      setFinalHref(
        `${href}?utm_source=${utmSource}&utm_campaign=${utmCampaign}`
      );
    }
  }, [searchParams, href]);

  return (
    <a href={finalHref} {...props}>
      {children}
    </a>
  );
};

export default CustomLink;

Use example:

 <CustomLink
   href="https://www.example.com"
   target="_blank"
   rel="noopener noreferrer"
   style={{ flex: "1" }}
  >To Someplace</CustomLink>

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202864

You may need to "forward" the current query along to the next route path using the URLObject syntax.

Example:

const router = useRouter();

...

router.push({
  pathname: "/profile", // <-- new target path
  query: router.query   // <-- any current "queryString"
});

Upvotes: 3

Related Questions