Skip to content

Commit

Permalink
Update next.js instructions for app directory
Browse files Browse the repository at this point in the history
Fixes #44
  • Loading branch information
derrickreimer authored Feb 20, 2023
1 parent fa66d57 commit a027939
Showing 1 changed file with 38 additions and 29 deletions.
67 changes: 38 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,11 @@ setSite('A_DIFFERENT_FATHOM_ID');

This library is JavaScript framework-agnostic. Below are some usage examples with popular frameworks.

### Next.js (v12.x)
### Next.js

> **Note:** This method is not currently compatible with v13 experimental changes (see [issue #44](https://github.com/derrickreimer/fathom-client/issues/44)).
#### Using `pages` directory (v12 and older)

> If you are using the latest Next.js beta with the `app` directory, see the modified instructions below.
Create an `_app.js` file in your `pages` directory, [like this](https://nextjs.org/docs#custom-app):

Expand Down Expand Up @@ -220,38 +222,19 @@ function App({ Component, pageProps }) {
export default App;
```

or if using the experimental `appDir` option, add a client component to your root `layout.tsx` file.

```tsx
// layout.tsx
#### Using the experimental `app` directory (v13)

import Fathom from "./Fathom"

export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<head>
</head>
<body>
<Fathom />
<Page>{children}</Page>
</body>
</html>
)
}
```

and create a client component like so
Create a `Fathom` client component:

```tsx
// Fathom.tsx
'use client'

import { load, trackPageview } from 'fathom-client'
import { useEffect } from 'react'
import { useEffect, Suspense } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'

export default function Fathom() {
function TrackPageView() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
Expand All @@ -260,13 +243,39 @@ export default function Fathom() {
})
}, [])

// Record a pageview when route changes
useEffect(() => {
trackPageview()

// Record a pageview when route changes
trackPageview();
}, [pathname, searchParams])

return null
return null;
}

export default function Fathom() {
return <Suspense fallback={null}>
<TrackPageView />
</Suspense>
}
```

Then, add the client component to your root `layout.tsx` file:

```tsx
// layout.tsx

import Fathom from "./Fathom"

export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<head>
</head>
<body>
<Fathom />
<Page>{children}</Page>
</body>
</html>
)
}
```

Expand Down

0 comments on commit a027939

Please sign in to comment.