forked from kremalicious/blog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchResults.tsx
79 lines (74 loc) · 1.84 KB
/
SearchResults.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import React, { ReactElement } from 'react'
import ReactDOM from 'react-dom'
import { graphql, useStaticQuery } from 'gatsby'
import PostTeaser from '../PostTeaser'
import SearchResultsEmpty from './SearchResultsEmpty'
import * as styles from './SearchResults.module.css'
export interface Results {
slug: string
}
const query = graphql`
query SearchResults {
allMarkdownRemark {
edges {
node {
...PostTeaser
}
}
}
}
`
function SearchResultsPure({
searchQuery,
results,
toggleSearch,
posts
}: {
posts: Queries.SearchResultsQuery['allMarkdownRemark']['edges']
searchQuery: string
results: Results[]
toggleSearch(): void
}) {
return (
<div className={styles.searchResults}>
{results.length > 0 ? (
<ul className={styles.results}>
{results.map((page: { slug: string }) =>
posts
.filter(({ node }) => node.fields.slug === page.slug)
.map(({ node }) => (
<li key={page.slug}>
<PostTeaser post={node} toggleSearch={toggleSearch} />
</li>
))
)}
</ul>
) : (
<SearchResultsEmpty searchQuery={searchQuery} results={results} />
)}
</div>
)
}
export default function SearchResults({
searchQuery,
results,
toggleSearch
}: {
searchQuery: string
results: Results[]
toggleSearch(): void
}): ReactElement {
const data = useStaticQuery<Queries.SearchResultsQuery>(query)
const posts = data.allMarkdownRemark.edges
// creating portal to break out of DOM node we're in
// and render the results in content container
return ReactDOM.createPortal(
<SearchResultsPure
posts={posts}
results={results}
searchQuery={searchQuery}
toggleSearch={toggleSearch}
/>,
document.getElementById('document')
)
}