daniel-ac-martin / NotGovUK

An implementation of the GOV.UK Design System in React that provides support for writing internal applications in addition to public ones.
https://not-gov.uk/
MIT License
27 stars 8 forks source link

Abstract the router requirement #858

Open RobinKnipe opened 9 months ago

RobinKnipe commented 9 months ago

Currently there is a hard dependency on react-router which means the project can't be used in other routing scenarios (e.g. Next.JS). By abstracting the routing, the project could be made to work with other SSR environments.

daniel-ac-martin commented 7 months ago

@RobinKnipe: Any ideas on how we can do this in practice? - I'd rather not drop support for react-router.

BTW, how does Next.js do this? Does it magically intercept normal <a> links rather than using a React component? Or do we need to find a way to switch to Next's version of <Link>?

BenJenkinson commented 6 months ago

Next.js has its own <Link> component which renders as an <a> tag

📚 https://nextjs.org/docs/app/api-reference/components/link

It's used in much the same way

<Link href="/dashboard">Dashboard</Link>
// Navigate to /about?name=test
<Link
  href={{
    pathname: '/about',
    query: { name: 'test' },
  }}
>
  About
</Link>

It does have some differences though; it is intended only for internal links and throws a warning if used for external ones.

Invalid hrefs include external sites (https://google.com) and mailto: links. In the past, usage of these invalid hrefs could have gone unnoticed, but since they can cause unexpected behavior we now show a warning in development for them.

📚 https://github.com/vercel/next.js/blob/canary/errors/invalid-href-passed.mdx

daniel-ac-martin commented 6 months ago

In that case, it's the same as it's always been.

I suppose the question is can we detect the context we are in? i.e. A react-router or a next-router? (Perhaps via a literal React 'Context'?) If we can do that, we can simply switch between the relevant upstream Link components in our own Link component.

RobinKnipe commented 6 months ago

I believe Next has a build phase - it attempts to do SSG and the necessary processing for asset creation (CSS/JS/etc) - so you would know then whether the context were Next or not.

daniel-ac-martin commented 3 weeks ago

Next seems to detect it's own context here: https://github.com/vercel/next.js/blob/6ac4fd6ef84c4b0367ebfd122d88d4af3cd146fb/packages/next/src/client/link.tsx#L313

daniel-ac-martin commented 3 weeks ago

Similar code in react-router: https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/index.tsx#L964