-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSearchBar.js
71 lines (60 loc) · 1.97 KB
/
SearchBar.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
import React, { useState } from 'react';
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args);
}, wait);
};
}
export default function SearchBarWrapper(props) {
let [searchResults, setResults] = useState([])
function search(e) {
if (e.target.value.length <3) return
fetch('http://localhost:5000/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: e.target.value,
}),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
setResults(data)
})
.catch((error) => {
console.error('Error:', error);
});
}
return (
<>
<input type="text"
placeholder="Search"
onChange={debounce(search, 300)}
onBlur={search}
onSubmit={search}
style={{padding:"7px 15px", border: "2px solid #CCC", borderRadius: 5}} />
{searchResults && searchResults.length > 0 &&
<div style={{
background: "white",
color: "black",
padding: 20,
position: "absolute",
border: "1px solid #CCC",
}}>
{searchResults.map((hit, index) => {
return <div key={index} style={{padding:3}}><a
style={{color: "blue", padding: 3}}
href={"/" + hit.url}>{hit.title}</a></div>
})}
</div>
}
</>
);
}