From a29a98a44d6ef944043e71e9a8964c28a57768b8 Mon Sep 17 00:00:00 2001
From: Raphael Arce <raphael.arce@ts.berlin>
Date: Thu, 22 Aug 2024 11:55:41 +0200
Subject: [PATCH] feat: add dynamic page titles

Signed-off-by: Raphael Arce <raphael.arce@ts.berlin>
---
 generate.js                  | 6 +++++-
 index.html                   | 2 +-
 src/App.tsx                  | 4 ++++
 src/hooks/use-page-title.tsx | 8 ++++++++
 4 files changed, 18 insertions(+), 2 deletions(-)
 create mode 100644 src/hooks/use-page-title.tsx

diff --git a/generate.js b/generate.js
index 3656698..b71f465 100644
--- a/generate.js
+++ b/generate.js
@@ -12,14 +12,18 @@ const toAbsolute = (p) => path.resolve(__dirname, p)
 const template = fs.readFileSync(toAbsolute('dist/index.html'), 'utf-8');
 const { render } = await import('./dist/server/entry-server.js');
 const { routes } = await import('./dist/assets/routes/routes.js');
+const { content } = await import('./dist/assets/content/content.js');
 
 function generateStaticPages() {
   for (const { path } of routes) {
     console.log('path:', path);
 
     const appHtml = render(path)
+    const pageTitle = content[path].title
 
-    const html = template.replace(`<!--app-html-->`, appHtml)
+    const html = template
+      .replace('<title></title>', `<title>${pageTitle}</title>`)
+      .replace(`<!--app-html-->`, appHtml)
 
     const filePath = `dist${path}index.html`
     writeFileSyncRecursive(toAbsolute(filePath), html)
diff --git a/index.html b/index.html
index 6cff60a..630f7fa 100644
--- a/index.html
+++ b/index.html
@@ -4,7 +4,7 @@
     <meta charset="UTF-8" />
     <link rel="icon" type="image/svg+xml" href="/vite.svg" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
-    <title>Vite React SSG</title>
+    <title></title>
   </head>
   <body>
     <div id="root"><!--app-html--></div>
diff --git a/src/App.tsx b/src/App.tsx
index e7de309..9fb2240 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -2,10 +2,14 @@ import React from "react";
 import { Route, Routes } from 'react-router-dom'
 import { routes } from './routes/routes'
 import { content } from "./content/content";
+import { usePageTitle } from "./hooks/use-page-title";
 
 const pages: Record<string, { default: React.FC }> = import.meta.glob('./pages/**/*.tsx', { eager: true })
 
 export function App() {
+
+  usePageTitle();
+
   return (
     <>
       <nav>
diff --git a/src/hooks/use-page-title.tsx b/src/hooks/use-page-title.tsx
new file mode 100644
index 0000000..7588649
--- /dev/null
+++ b/src/hooks/use-page-title.tsx
@@ -0,0 +1,8 @@
+import {useEffect} from "react";
+import {content} from "../content/content.ts";
+
+export function usePageTitle() {
+	useEffect(() => {
+		document.title = content[window.location.pathname].title
+	}, [])
+}
\ No newline at end of file