Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

javascript - Add query string to ALL links in application

Here is the situation... I have a Next.js app that has been up for a bit, we have a ton of code already writen.

Recently we started running some ads and we need to understand how they are doing...

Someone could land on our site with either of the two URLs.

www.site.com/page // user came to our site NOT from ad
www.site.com/page?ad=campaign1 // user came from one of our ads.

If a user comes to our site with the "ad" querystring, I would like to append that to ALL links on our site.

How would I go about doing that in react/nextjs? we have a ton of components already built and even some blog posts where we are just rendoring raw HTML.

Without going and editing a zillion components. How would I go about appending the query string to all links?

Thanks

question from:https://stackoverflow.com/questions/66054534/add-query-string-to-all-links-in-application

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could create a custom Link component, as a wrapper to next/link, that would check for the query string and add it to the href of the Next.js Link.

// components/link.jsx

import NextLink from 'next/link';
import { useRouter } from 'next/router';

const Link = ({ children, href }) => {
  const router = useRouter();
  const [, queryString] = router.asPath.split('?');
  const hrefWithQuery = `${href}${queryString ? `?${queryString}` : ''}`;
  return <NextLink href={hrefWithQuery}>{children}</NextLink>;
};

export default Link;

Then replace all imports of next/link with the path to the new component wherever they are used (a simple search & replace would do).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...