feat: autocomplete for search

Co-authored-by: Alex Sparkes <turbomarshmello@gmail.com>
This commit is contained in:
David Ralph
2021-05-01 18:29:07 +01:00
parent 7942c367a7
commit a1b6832747
21 changed files with 221 additions and 14 deletions

View File

@@ -0,0 +1,77 @@
import React from 'react';
import './autocomplete.scss';
export default class Autocomplete extends React.Component {
constructor(props) {
super(props);
this.state = {
filtered: [],
showList: false,
input: ''
};
this.enabled = (localStorage.getItem('autocomplete') === 'true')
}
onChange = (e) => {
if (this.enabled === false) {
return this.setState({
input: e.target.value
});
}
this.setState({
filtered: this.props.suggestions.filter((suggestion) => suggestion.toLowerCase().indexOf(e.target.value.toLowerCase()) > -1),
showList: true,
input: e.target.value
});
this.props.onChange(e.target.value);
};
onClick = (e) => {
this.setState({
filtered: [],
showList: false,
input: e.target.innerText
});
this.props.onClick(e.target.innerText);
};
render() {
let autocomplete = null;
if (this.state.showList && this.state.input) {
if (this.state.filtered.length && localStorage.getItem('autocomplete') === 'true') {
autocomplete = (
<ul className='suggestions'>
{this.state.filtered.map((suggestion) => {
let className;
return (
<li className={className} key={suggestion} onClick={this.onClick}>
{suggestion}
</li>
);
})}
</ul>
);
}
}
return (
<>
<input
type='text'
onChange={this.onChange}
value={this.state.input}
name={this.props.name || 'name'}
placeholder={this.props.placeholder || ''}
autoComplete='off'
id={this.props.id || ''} />
{autocomplete}
</>
);
}
}

View File

@@ -0,0 +1,38 @@
.suggestions {
text-align: left;
font-size: calc(5px + 1.2vmin);
background-color: rgba(0, 0, 0, 0.5);
border-top-width: 0;
list-style: none;
margin-top: 40px;
max-height: 143px;
overflow: hidden;
position: relative;
display: inline-block;
margin-left: 40px;
border-radius: 24px;
width: 430px;
opacity: 0;
li {
padding: 0.5rem;
padding-left: 20px;
&:hover {
background-color: rgba(0, 0, 0, 0.5);
cursor: pointer;
}
}
}
.searchBar {
input[type=text]:focus+.suggestions {
opacity: 1;
}
}
@media screen and (min-width: 1400px) {
.suggestions {
margin-top: 50px;
}
}