1
0
Fork 0
blog/src/components/molecules/Search/SearchResults.tsx

80 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-05-22 14:38:19 +02:00
import React, { ReactElement } from 'react'
2019-10-02 20:48:59 +02:00
import { graphql, useStaticQuery } from 'gatsby'
2023-01-29 22:58:19 +01:00
import ReactDOM from 'react-dom'
2019-11-24 14:29:25 +01:00
import PostTeaser from '../PostTeaser'
import * as styles from './SearchResults.module.css'
2023-01-29 22:58:19 +01:00
import SearchResultsEmpty from './SearchResultsEmpty'
2019-10-16 01:45:30 +02:00
export interface Results {
slug: string
}
2019-10-02 13:35:50 +02:00
const query = graphql`
query SearchResults {
2019-10-02 13:35:50 +02:00
allMarkdownRemark {
edges {
node {
2019-11-24 14:29:25 +01:00
...PostTeaser
2019-10-02 13:35:50 +02:00
}
}
}
}
`
2019-10-16 01:45:30 +02:00
function SearchResultsPure({
2019-10-02 13:35:50 +02:00
searchQuery,
results,
2019-10-16 01:45:30 +02:00
toggleSearch,
posts
2019-10-02 13:35:50 +02:00
}: {
posts: Queries.SearchResultsQuery['allMarkdownRemark']['edges']
2019-10-02 13:35:50 +02:00
searchQuery: string
2019-10-16 01:45:30 +02:00
results: Results[]
2019-10-02 13:35:50 +02:00
toggleSearch(): void
}) {
2019-10-16 01:45:30 +02:00
return (
<div className={styles.searchResults}>
2021-03-07 02:48:05 +01:00
{results.length > 0 ? (
<ul className={styles.results}>
2021-03-07 02:48:05 +01:00
{results.map((page: { slug: string }) =>
posts
.filter(({ node }) => node.fields.slug === page.slug)
.map(({ node }) => (
2021-03-07 02:48:05 +01:00
<li key={page.slug}>
<PostTeaser post={node} toggleSearch={toggleSearch} />
</li>
))
)}
</ul>
) : (
<SearchResultsEmpty searchQuery={searchQuery} results={results} />
)}
2019-10-16 01:45:30 +02:00
</div>
)
}
export default function SearchResults({
searchQuery,
results,
toggleSearch
}: {
searchQuery: string
results: Results[]
toggleSearch(): void
2020-05-22 14:38:19 +02:00
}): ReactElement {
const data = useStaticQuery<Queries.SearchResultsQuery>(query)
2019-10-16 01:45:30 +02:00
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}
/>,
2019-10-02 20:48:59 +02:00
document.getElementById('document')
2019-10-02 13:35:50 +02:00
)
}