Skip to content

Commit 99eb960

Browse files
committed
Fix Pagefind search page to use web components
The dynamic import approach for pagefind-ui.js doesn't work reliably with Gatsby's webpack bundling. Switch to loading pagefind-component-ui.js via a script tag and using the <pagefind-searchbox> and <pagefind-results> web components instead.
1 parent 2a3b789 commit 99eb960

1 file changed

Lines changed: 23 additions & 19 deletions

File tree

src/pages/search.js

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,41 @@ import React, { useEffect, useRef } from "react";
22
import Layout from "../components/Layout";
33

44
const SearchPage = () => {
5-
const searchRef = useRef(null);
5+
const containerRef = useRef(null);
66

77
useEffect(() => {
8-
const loadPagefind = async () => {
9-
if (!searchRef.current) return;
8+
if (!containerRef.current) return;
109

11-
// Load Pagefind UI CSS
12-
const link = document.createElement("link");
13-
link.rel = "stylesheet";
14-
link.href = "/pagefind/pagefind-ui.css";
15-
document.head.appendChild(link);
10+
// Load Pagefind component UI CSS
11+
const link = document.createElement("link");
12+
link.rel = "stylesheet";
13+
link.href = "/pagefind/pagefind-component-ui.css";
14+
document.head.appendChild(link);
1615

17-
// Load and initialize Pagefind UI
18-
const PagefindUI = await import(
19-
/* webpackIgnore: true */ "/pagefind/pagefind-ui.js"
20-
);
21-
new PagefindUI.default({
22-
element: searchRef.current,
23-
showSubResults: true,
24-
showImages: false,
25-
});
16+
// Load Pagefind component UI JS (web components)
17+
const script = document.createElement("script");
18+
script.src = "/pagefind/pagefind-component-ui.js";
19+
script.type = "module";
20+
script.onload = () => {
21+
// Insert the web components after the script loads
22+
containerRef.current.innerHTML = `
23+
<pagefind-searchbox></pagefind-searchbox>
24+
<pagefind-results></pagefind-results>
25+
`;
2626
};
27+
document.head.appendChild(script);
2728

28-
loadPagefind();
29+
return () => {
30+
document.head.removeChild(link);
31+
document.head.removeChild(script);
32+
};
2933
}, []);
3034

3135
return (
3236
<Layout>
3337
<div>
3438
<h1 className="cabin f4 f3-ns">Search</h1>
35-
<div ref={searchRef}></div>
39+
<div ref={containerRef}></div>
3640
</div>
3741
</Layout>
3842
);

0 commit comments

Comments
 (0)