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