-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathreact-search-lunr.js
44 lines (38 loc) · 1.07 KB
/
react-search-lunr.js
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
import React from 'react'
import PropTypes from 'prop-types'
import lunr from 'lunr'
class ReactLunr extends React.Component {
constructor(props) {
super(props)
const index = lunr(function() {
this.ref(props.id)
props.fields.forEach(field => this.field(field))
props.documents.forEach(doc => this.add(doc))
})
this.state = { index, documents: props.documents }
}
getResults(filter) {
if (!filter) return []
const results = this.state.index
.search(filter) // search the index
.map(({ ref, ...rest }) => ({
ref,
item: this.state.documents.find(m => m[this.props.id] == ref),
...rest
})) // attach each item
console.log(filter, results)
return results
}
render() {
const results = this.getResults(this.props.filter)
return this.props.children(results)
}
}
ReactLunr.propTypes = {
fields: PropTypes.arrayOf(PropTypes.string),
id: PropTypes.string,
documents: PropTypes.arrayOf(PropTypes.object),
filter: PropTypes.string,
children: PropTypes.func
}
export default ReactLunr