Skip to content

Instantly share code, notes, and snippets.

@zerolethanh
Last active February 10, 2021 13:22
Show Gist options
  • Save zerolethanh/61ff7297c1aaeb673d747fd25f558aed to your computer and use it in GitHub Desktop.
Save zerolethanh/61ff7297c1aaeb673d747fd25f558aed to your computer and use it in GitHub Desktop.
search with fuse.js
import {Avatar, Input, Popover} from 'antd';
import React, {useState} from 'react';
import Fuse from 'fuse.js';
import {useGlobal} from 'reactn';
const {Search} = Input;
export default function SearchComponent() {
const [gPosts] = useGlobal('gPosts');
const [found, setFound] = useState(null);
const fuse = React.useMemo(() => {
return new Fuse(gPosts, {
keys: ['title', 'content'],
useExtendedSearch: true,
});
}, [gPosts]);
function onChange(e) {
const searchText = e.target.value;
if (!searchText) return;
const results = fuse.search(`'${searchText}`);
const items = results.map(result => result.item);
// console.log(items);
setFound(items);
}
if (!gPosts) return null;
return (
<div className={'search-com'}>
<Popover content={
found &&
<ul>
{
found.map(p =>
<li
onClick={() => window.open(`/edit?id=${p.id}`)}
>
<a>{p.title}</a> by
<Avatar
src={p.author.photoURL}/>
{p.author.displayName}
</li>,
)
}
</ul>
} title="Found" trigger="hover">
<Search
// onSearch={onSearch}
allowClear
enterButton
onChange={onChange}
placeholder={'search'}
/>
</Popover>
<style jsx>{
`
.search-com {
display: flex;
align-items: center;
margin-right: 20px;
}
`
}</style>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment