47 lines
1.1 KiB
JavaScript
47 lines
1.1 KiB
JavaScript
import React, { useState, useRef } from 'react';
|
|
import { useHistory, useLocation } from 'react-router-dom';
|
|
import queryString from 'query-string';
|
|
|
|
const getSearch = location => queryString.parse(location.search).q || '';
|
|
|
|
function Search() {
|
|
const history = useHistory();
|
|
const location = useLocation();
|
|
|
|
const [search, setSearch] = useState(getSearch(location));
|
|
const inputRef = useRef(null);
|
|
|
|
const searchArticles = (event) => {
|
|
const newSearch = event.target.value;
|
|
setSearch(newSearch);
|
|
if (newSearch.length >= 3) {
|
|
const searchQuery = queryString.stringify({ 'q': newSearch });
|
|
history.replace('/search?' + searchQuery);
|
|
} else {
|
|
history.replace('/');
|
|
}
|
|
}
|
|
|
|
const searchAgain = (event) => {
|
|
event.preventDefault();
|
|
const searchString = queryString.stringify({ 'q': event.target[0].value });
|
|
history.push('/search?' + searchString);
|
|
inputRef.current.blur();
|
|
}
|
|
|
|
return (
|
|
<span className='search'>
|
|
<form onSubmit={searchAgain}>
|
|
<input
|
|
placeholder='Search...'
|
|
value={search}
|
|
onChange={searchArticles}
|
|
ref={inputRef}
|
|
/>
|
|
</form>
|
|
</span>
|
|
);
|
|
}
|
|
|
|
export default Search;
|