/
SearchExampleCategory.js
92 lines (77 loc) · 2.38 KB
/
SearchExampleCategory.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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
import _ from 'lodash'
import faker from 'faker'
import React, { Component } from 'react'
import { Search, Grid, Header, Segment } from 'semantic-ui-react'
const initialState = { isLoading: false, results: [], value: '' }
const getResults = () =>
_.times(5, () => ({
title: faker.company.companyName(),
description: faker.company.catchPhrase(),
image: faker.internet.avatar(),
price: faker.finance.amount(0, 100, 2, '$'),
}))
const source = _.range(0, 3).reduce((memo) => {
const name = faker.hacker.noun()
// eslint-disable-next-line no-param-reassign
memo[name] = {
name,
results: getResults(),
}
return memo
}, {})
export default class SearchExampleCategory extends Component {
state = initialState
handleResultSelect = (e, { result }) => this.setState({ value: result.title })
handleSearchChange = (e, { value }) => {
this.setState({ isLoading: true, value })
setTimeout(() => {
if (this.state.value.length < 1) return this.setState(initialState)
const re = new RegExp(_.escapeRegExp(this.state.value), 'i')
const isMatch = (result) => re.test(result.title)
const filteredResults = _.reduce(
source,
(memo, data, name) => {
const results = _.filter(data.results, isMatch)
if (results.length) memo[name] = { name, results } // eslint-disable-line no-param-reassign
return memo
},
{},
)
this.setState({
isLoading: false,
results: filteredResults,
})
}, 300)
}
render() {
const { isLoading, value, results } = this.state
return (
<Grid>
<Grid.Column width={8}>
<Search
category
loading={isLoading}
onResultSelect={this.handleResultSelect}
onSearchChange={_.debounce(this.handleSearchChange, 500, {
leading: true,
})}
results={results}
value={value}
/>
</Grid.Column>
<Grid.Column width={8}>
<Segment>
<Header>State</Header>
<pre style={{ overflowX: 'auto' }}>
{JSON.stringify(this.state, null, 2)}
</pre>
<Header>Options</Header>
<pre style={{ overflowX: 'auto' }}>
{JSON.stringify(source, null, 2)}
</pre>
</Segment>
</Grid.Column>
</Grid>
)
}
}