File tree Expand file tree Collapse file tree 3 files changed +20
-10
lines changed Expand file tree Collapse file tree 3 files changed +20
-10
lines changed Original file line number Diff line number Diff line change 1
1
import styles from '@/styles/SearchBar.module.scss' ;
2
+ import { useRef } from 'react' ;
2
3
3
- const SearchBar = ( { posts, setSearchTerm, setSearchResults } ) => {
4
- const handleChange = e => {
5
- if ( ! e . target . value ) return setSearchResults ( null ) ;
6
- const results = posts . filter ( post =>
7
- post . title . toLowerCase ( ) . includes ( e . target . value . toLowerCase ( ) )
4
+ const SearchBar = ( { items, setSearchTerm, setSearchResults } ) => {
5
+ const searchInput = useRef ( null ) ;
6
+ const search = ( ) => {
7
+ const searchTerm = searchInput . current . value ;
8
+ if ( ! searchTerm ) return setSearchResults ( null ) ;
9
+ const results = items . filter (
10
+ post =>
11
+ post . title . toLowerCase ( ) . includes ( searchTerm . toLowerCase ( ) ) ||
12
+ post . tagList . some ( tag =>
13
+ tag . toLowerCase ( ) . includes ( searchTerm . toLowerCase ( ) )
14
+ )
8
15
) ;
9
16
setSearchResults ( results ) ;
10
- setSearchTerm ( e . target . value ) ;
17
+ setSearchTerm ( searchTerm ) ;
11
18
} ;
12
19
return (
13
20
< div className = { styles . searchBar } >
14
21
< input
22
+ ref = { searchInput }
15
23
type = 'search'
16
24
placeholder = 'keyword or topic'
17
- onChange = { handleChange }
25
+ onChange = { search }
18
26
/>
19
- < button type = 'submit' > Search</ button >
27
+ < button type = 'submit' onClick = { search } >
28
+ Search
29
+ </ button >
20
30
</ div >
21
31
) ;
22
32
} ;
Original file line number Diff line number Diff line change @@ -25,7 +25,7 @@ export default function Blog({ posts }) {
25
25
title = { searchResults ? '' : 'Latest Posts' }
26
26
/>
27
27
< SearchBar
28
- posts = { posts }
28
+ items = { posts }
29
29
setSearchTerm = { setSearchTerm }
30
30
setSearchResults = { setSearchResults }
31
31
/>
Original file line number Diff line number Diff line change 31
31
background : url (' /images/svg/search.svg' );
32
32
background-size : cover ;
33
33
background-repeat : no-repeat ;
34
- margin : 0.5rem 1rem 0.5rem 0 ;
34
+ margin : 0.5rem 1rem 0.5rem 1 rem ;
35
35
cursor : pointer ;
36
36
}
37
37
}
You can’t perform that action at this time.
0 commit comments