-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchBar.js
More file actions
48 lines (43 loc) · 1.27 KB
/
SearchBar.js
File metadata and controls
48 lines (43 loc) · 1.27 KB
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
import React, { useState } from 'react';
const SearchBar = ({ onSearch, suggestions }) => {
const [inputValue, setInputValue] = useState('');
const [showSuggestions, setShowSuggestions] = useState(false);
const handleInputChange = (e) => {
const value = e.target.value;
setInputValue(value);
setShowSuggestions(true);
onSearch(value);
};
const handleSuggestionClick = (suggestion) => {
setInputValue(suggestion);
setShowSuggestions(false);
onSearch(suggestion);
};
return (
<div className="search-bar">
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Search by country or capital..."
/>
{showSuggestions && inputValue && (
<ul className="suggestions-list">
{suggestions
.filter((suggestion) =>
suggestion.toLowerCase().includes(inputValue.toLowerCase())
)
.map((suggestion, index) => (
<li
key={index}
onClick={() => handleSuggestionClick(suggestion)}
>
{suggestion}
</li>
))}
</ul>
)}
</div>
);
};
export default SearchBar;