refactor: Refactor Search component to use hooks
This commit is contained in:
@@ -1,51 +1,46 @@
|
|||||||
import React, { Component } from 'react';
|
import React, { useState, useRef } from 'react';
|
||||||
import { withRouter } from 'react-router-dom';
|
import { useHistory, useLocation } from 'react-router-dom';
|
||||||
import queryString from 'query-string';
|
import queryString from 'query-string';
|
||||||
|
|
||||||
const getSearch = props => queryString.parse(props.location.search).q;
|
const getSearch = location => queryString.parse(location.search).q || '';
|
||||||
|
|
||||||
class Search extends Component {
|
function Search() {
|
||||||
constructor(props) {
|
const history = useHistory();
|
||||||
super(props);
|
const location = useLocation();
|
||||||
|
|
||||||
this.state = {search: getSearch(this.props)};
|
const [search, setSearch] = useState(getSearch(location));
|
||||||
this.inputRef = React.createRef();
|
const inputRef = useRef(null);
|
||||||
}
|
|
||||||
|
|
||||||
searchArticles = (event) => {
|
const searchArticles = (event) => {
|
||||||
const search = event.target.value;
|
const newSearch = event.target.value;
|
||||||
this.setState({search: search});
|
setSearch(newSearch);
|
||||||
if (search.length >= 3) {
|
if (newSearch.length >= 3) {
|
||||||
const searchQuery = queryString.stringify({ 'q': search });
|
const searchQuery = queryString.stringify({ 'q': newSearch });
|
||||||
this.props.history.replace('/search?' + searchQuery);
|
history.replace('/search?' + searchQuery);
|
||||||
} else {
|
} else {
|
||||||
this.props.history.replace('/');
|
history.replace('/');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
searchAgain = (event) => {
|
const searchAgain = (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const searchString = queryString.stringify({ 'q': event.target[0].value });
|
const searchString = queryString.stringify({ 'q': event.target[0].value });
|
||||||
this.props.history.push('/search?' + searchString);
|
history.push('/search?' + searchString);
|
||||||
this.inputRef.current.blur();
|
inputRef.current.blur();
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
return (
|
||||||
const search = this.state.search;
|
<span className='search'>
|
||||||
|
<form onSubmit={searchAgain}>
|
||||||
return (
|
<input
|
||||||
<span className='search'>
|
placeholder='Search...'
|
||||||
<form onSubmit={this.searchAgain}>
|
value={search}
|
||||||
<input
|
onChange={searchArticles}
|
||||||
placeholder='Search...'
|
ref={inputRef}
|
||||||
value={search}
|
/>
|
||||||
onChange={this.searchArticles}
|
</form>
|
||||||
ref={this.inputRef}
|
</span>
|
||||||
/>
|
);
|
||||||
</form>
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default withRouter(Search);
|
export default Search;
|
||||||
|
|||||||
Reference in New Issue
Block a user