# Client-side routing

> Learn how to integrate Cimpress UI components with your client-side routing framework.

Source: https://ui.cimpress.io/dev-guides/client-side-routing/

Cimpress UI components such as `Link`, `Menu`, and many others support rendering elements as links that perform navigation.
Each component that supports link behavior accepts the `href` prop, which causes the component to render an `<a>` element.
Other link DOM props such as `target` and `download` are also supported.

```tsx
<Link href="https://example.com/" target="_blank">
  Open example site
</Link>
```

By default, links perform native browser navigation when they are interacted with.
However, many apps and frameworks use client-side routers to avoid a full page reload when navigating between pages.
The `RouterProvider` component configures all Cimpress UI components within it to navigate using the client-side router you provide.
Set this up once in the root of your app, and any Cimpress UI component with the `href` prop will automatically navigate using your router.

Note that external links to different origins will not trigger client-side routing, and will use native browser navigation.
Additionally, if the link has a target other than `'_self'`, uses the `download` attribute, or the user presses modifier keys such as Command or Alt to change the default behavior,
browser native navigation will occur instead of client-side routing.

All Cimpress UI link components accept a `routerOptions` prop, which is an object passed to the client-side router's `navigate` function as the second argument.
This can be used to control any router-specific behaviors, such as scrolling, replacing instead of pushing to the history, etc.

```tsx
<Link href="/login" routerOptions={{ replace: true }}>
  Login
</Link>
```

For most apps, `RouterProvider` is all you need. If you need features that only your router's own link component provides,
such as prefetching, you can [render your router's link component](#rendering-router-links) for `Link`, `LinkButton`, and `IconLinkButton`.

## Integrating client-side routing with Cimpress UI

:::note
These steps show a general pattern for integrating client-side routing with Cimpress UI. Continue reading this guide
for integration examples using specific frameworks.
:::

1. Wrap your application in Cimpress UI's `RouterProvider`:

   ```tsx title="src/app.tsx" del={5} ins={1-2,6-8}
   import { RouterProvider } from '@cimpress-ui/react';

   export function App() {
     return (
       {/* ... */}
       <RouterProvider>
         {/* ... */}
       </RouterProvider>
     );
   }
   ```

2. Obtain a function from your routing framework that performs client-side navigation programmatically.
   Pass this function to `RouterProvider` in the `navigate` prop:

   ```tsx title="src/app.tsx" del={8} ins={2,5-6,9}
   import { RouterProvider } from '@cimpress-ui/react';
   import { useNavigate } from 'your-router';

   export function App() {
     const navigate = useNavigate();

     return (
       <RouterProvider>
       <RouterProvider navigate={navigate}>
         {/* ... */}
       </RouterProvider>
     );
   }
   ```

3. If your router supports converting router-specific `href`s to native HTML `href`s,
   pass the function that does this to `RouterProvider` in the `useHref` prop:

   ```tsx title="src/app.tsx" del={2,9} ins={3,10}
   import { RouterProvider } from '@cimpress-ui/react';
   import { useNavigate } from 'your-router';
   import { useNavigate, useHref } from 'your-router';

   export function App() {
     const navigate = useNavigate();

     return (
       <RouterProvider navigate={navigate}>
       <RouterProvider navigate={navigate} useHref={useHref}>
         {/* ... */}
       </RouterProvider>
     );
   }
   ```

4. Configure the `RouterConfig` type globally using a type provided by your router.
   This ensures type safety and autocomplete support for all link components.

   ```ts title="src/declarations.d.ts" ins={1-8}
   import type { Href, RouterOptions } from 'your-router';

   declare module '@cimpress-ui/react' {
     interface RouterConfig {
       href: Href;
       routerOptions: RouterOptions;
     }
   }
   ```

## Framework-specific examples

### React Router

:::note
This guide applies to React Router v6.
:::

The `useNavigate` hook from `react-router-dom` returns a `navigate` function that you can pass to `RouterProvider`.
The `useHref` hook can also be provided if you're using React Router's `basename` option.

Make sure that:

- The component that calls `useNavigate` and renders `RouterProvider` is inside the router component (e.g. `BrowserRouter`), so that it has access to React Router's internal context.
- The React Router's `Routes` element should be defined inside Cimpress UI's `RouterProvider` so that links inside the rendered routes have access to the router.

**src/main.tsx**

```tsx del={12} ins={3,13-15}
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './app.js';

import '@fontsource-variable/open-sans/wght.css';
import '@fontsource-variable/open-sans/wght-italic.css';
import '@cimpress-ui/react/styles.css';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>,
);
```

**src/app.tsx**

```tsx del={1} ins={2-3,7-8,10,16}
import { Route, Routes } from 'react-router-dom';
import { Route, Routes, useHref, useNavigate } from 'react-router-dom';
import { RouterProvider } from '@cimpress-ui/react';
import { HomePage } from './pages/home-page.js';

export function App() {
  const navigate = useNavigate();

  return (
    <RouterProvider navigate={navigate} useHref={useHref}>
      {/* ... */}
      <Routes>
        <Route path="/" element={<HomePage />} />
        {/* ... */}
      </Routes>
    </RouterProvider>
  );
}
```

**src/declarations.d.ts**

```ts ins={1-7}
import type { NavigateOptions } from 'react-router-dom';

declare module '@cimpress-ui/react' {
  interface RouterConfig {
    routerOptions: NavigateOptions;
  }
}
```

### Remix

Remix uses React Router under the hood, so the same `useNavigate` and `useHref` hooks described above also work in Remix apps.
`RouterProvider` should be rendered at the root of each page that includes Cimpress UI links, or in the root route to add it to all pages.

### Next.js app router

The [`useRouter`](https://nextjs.org/docs/app/api-reference/functions/use-router) hook from `next/navigation` returns a router object that can be used to perform navigation.
`RouterProvider` should be rendered from a client component at the root of each page or layout that includes Cimpress UI links.

**app/layout.tsx**

```tsx del={12} ins={3-5,7-8,13-15}
'use client';

import { useRouter } from 'next/navigation';
import { RouterProvider } from '@cimpress-ui/react';

export default function RootLayout({ children }) {
  const router = useRouter();

  return (
    <html>
      <body>
        {children}
        <RouterProvider navigate={router.push}>
          {children}
        </RouterProvider>
      </body>
    </html>
  );
}
```

**app/declarations.d.ts**

```ts ins={1-9}
import { useRouter } from 'next/navigation';

declare module '@cimpress-ui/react' {
  interface RouterConfig {
    routerOptions: NonNullable<
      Parameters<ReturnType<typeof useRouter>['push']>[1]
    >;
  }
}
```

If you are using the `basePath` configuration option, you'll need to configure an environment variable to access it.
Then, provide a custom `useHref` function to prepend `basePath` to the `href` for all links.

**next.config.js**

```ts ins={5-7}
const basePath = '...';

const nextConfig = {
  basePath,
  env: {
    BASE_PATH: basePath
  }
};
```

**app/layout.tsx**

```tsx del={14} ins={6-7,15}
'use client';

import { useRouter } from 'next/navigation';
import { RouterProvider } from '@cimpress-ui/react';

const useHref = (href: string) => process.env.BASE_PATH + href;

export default function RootLayout({ children }) {
  const router = useRouter();

  return (
    <html>
      <body>
        <RouterProvider navigate={router.push}>
        <RouterProvider navigate={router.push} useHref={useHref}>
          {children}
        </RouterProvider>
      </body>
    </html>
  );
}
```

### Next.js pages router

The [`useRouter`](https://nextjs.org/docs/pages/api-reference/functions/use-router) hook from `next/router` returns a router object that can be used to perform navigation.
`RouterProvider` should be rendered at the root of each page or layout that includes Cimpress UI links, or in `pages/_app.tsx` to add it to all pages.

**pages/\_app.tsx**

```tsx ins={2-3,6-7,9-11,13}
import type {AppProps} from 'next/app';
import {useRouter} from 'next/router'
import {RouterProvider} from '@cimpress-ui/react';

export default function MyApp({ Component, pageProps }: AppProps) {
  const router = useRouter();

  return (
    <RouterProvider
      navigate={(href, options) => router.push(href, undefined, options)}
    >
      <Component {...pageProps} />
    </RouterProvider>
  );
}
```

**declarations.d.ts**

```ts ins={1-9}
import type { NextRouter } from 'next/router';

declare module '@cimpress-ui/react' {
  interface RouterConfig {
    routerOptions: NonNullable<
      Parameters<NextRouter['push']>[2]
    >;
  }
}
```

If you are using the `basePath` configuration option, provide a `useHref` prop to `RouterProvider` to prepend it to links automatically.

```tsx title="pages/_app.tsx" ins={11}
import type { AppProps } from 'next/app';
import { useRouter } from 'next/router';
import { RouterProvider } from '@cimpress-ui/react';

export default function MyApp({ Component, pageProps }: AppProps) {
  const router = useRouter();

  return (
    <RouterProvider
      navigate={(href, options) => router.push(href, undefined, options)}
      useHref={(href: string) => router.basePath + href}
    >
      <Component {...pageProps} />
    </RouterProvider>
  );
}
```

## Rendering router links

`RouterProvider` handles client-side navigation for every Cimpress UI component, but it can't enable features that only your router's own link component offers,
such as prefetching a page when the link is hovered or scrolled into view.
For these cases, `Link`, `LinkButton`, and `IconLinkButton` accept a `render` prop.
It takes a function that gets the props of the DOM element and returns the element to render in its place, usually your router's link component.

Cimpress UI still handles the styling, accessibility, and interactions of the link. Your router's link component handles navigation and any router-specific features.

The rendered element depends on the link's state. An enabled link is rendered as an `<a>` element with an `href`.
A disabled link is rendered as a `<span>` element without one, so it can't be navigated to.
Check whether `'href' in props` to tell which element to render.

`LinkButton` and `IconLinkButton` disabled with a reason are rendered as a `<button>` element instead, so the `render` prop is ignored in that state.

:::caution
Follow these rules so you don't break the behavior and accessibility of the component:

- The function must render the expected element type: an `<a>` when `'href' in props`, otherwise a `<span>`.
- The function must render a single root element (no fragments).
- The function must pass all the props it receives, including `ref`, to the rendered element. If you add your own event handlers, merge them with the ones you received instead of replacing them.
:::

The `href` passed to the function has already been processed by `RouterProvider`'s `useHref` (if you provided one). Pass it to your router's link component as the destination.

### Next.js

```tsx ins={1,4}
import NextLink from 'next/link';
import { Link } from '@cimpress-ui/react';

<Link href="/about" render={(props) => ('href' in props ? <NextLink {...props} prefetch /> : <span {...props} />)}>
  About
</Link>;
```

### React Router

```tsx ins={1,6-8}
import { Link as RouterLink } from 'react-router';
import { Link } from '@cimpress-ui/react';

<Link
  href="/about"
  render={(props) =>
    'href' in props ? <RouterLink {...props} to={props.href} prefetch="intent" /> : <span {...props} />
  }
>
  About
</Link>;
```

### Creating a reusable link

To avoid repeating the `render` prop everywhere, wrap the Cimpress UI component in a component of your own:

```tsx title="src/components/app-link.tsx"
import { Link as RouterLink } from 'react-router';
import { Link, type LinkProps } from '@cimpress-ui/react';

export function AppLink(props: Omit<LinkProps, 'render'>) {
  return (
    <Link
      {...props}
      render={(linkProps) =>
        'href' in linkProps ? (
          <RouterLink {...linkProps} to={linkProps.href} prefetch="intent" />
        ) : (
          <span {...linkProps} />
        )
      }
    />
  );
}
```
