Open RobinKnipe opened 9 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>
?
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
href
s include external sites (https://google.com) andmailto:
links. In the past, usage of these invalidhref
s 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
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.
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.
Next seems to detect it's own context here: https://github.com/vercel/next.js/blob/6ac4fd6ef84c4b0367ebfd122d88d4af3cd146fb/packages/next/src/client/link.tsx#L313
Similar code in react-router: https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/index.tsx#L964
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.