'Connect Shopify Polaris links with Nextjs Links

When using Shopify Polaris, many internal components output a single static <a /> tag, this breaks my NextJS app experience since clicking on the link reloads the page.

How can I make Shopify Polaris links behave just like Nextjs ones with <Link /> component?



Solution 1:[1]

On your Polaris AppProvider you can provide a linkComponent component and Polaris will use that to render all links, then simple wrap it with nextjs Link component:

import React from 'react'
import Link from 'next/link'
import { AppProps } from 'next/app'
import { AppProvider } from '@shopify/polaris'
import { NextPage } from 'next'
import { LinkLikeComponentProps } from '@shopify/polaris/dist/types/latest/src/utilities/link'
import '@shopify/polaris/dist/styles.css'

/**
 * Connects Nextjs Link with Polaris Links
 * @param props
 * @returns
 */
function LinkWrapper(props: LinkLikeComponentProps) {
  const { children, url, ...rest } = props

  return (
    <Link href={url}>
      <a {...rest}>{children}</a>
    </Link>
  )
}

const MyApp: NextPage<AppProps> = function MyApp({
  Component,
  pageProps,
  router,
}) {
 

  return (
    <AppProvider
      linkComponent={LinkWrapper}
    >
      {/* ... */}
    </AppProvider>
  )
}

export default MyApp

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1