Skip to content

Instantly share code, notes, and snippets.

@Eightyplus
Created June 15, 2018 08:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eightyplus/63aba24abf1db13f79cf5793e20129b5 to your computer and use it in GitHub Desktop.
Save Eightyplus/63aba24abf1db13f79cf5793e20129b5 to your computer and use it in GitHub Desktop.
React auto-complete input
import React, { Component } from 'react';
export default class InputAutoComplete extends Component {
constructor (props) {
super(props);
this.options = ['britain', 'ireland', 'norway', 'sweden', 'denmark', 'germany', 'holland', 'belgium', 'france', 'spain', 'portugal', 'italy', 'switzerland'];
this.state = {
input: '',
selected: false
};
}
handleChange(event) {
return this.setState({
input: event.target.value
});
}
handleClick(option) {
return this.setState({
input: option
});
}
matches(input) {
const regex = new RegExp(input, 'i');
return this.options.filter(function(option) {
return option.match(regex) && option !== input;
});
}
onInputFocus(show) {
if (show) {
this.setState({selected: true})
} else {
setTimeout( () => this.setState({selected: false}), 500)
}
}
render() {
let styleSelect = {
position: 'absolute',
backgroundColor: '#f1f1f1',
minWidth: '160px',
boxShadow: '0px 8px 16px 0px rgba(0,0,0,0.2)',
zIndex: 1,
};
let styleOptions = {
color: 'black',
padding: '12px 16px',
display: 'block',
};
let autoComplete = null;
if (this.state.selected) {
autoComplete = (<div style={styleSelect}>{
this.matches(this.state.input).map( option => {
return <div style={styleOptions} onClick={ () => this.handleClick(option)}>{option}</div>;
})
}</div>);
}
return (
<div>
<input onChange={this.handleChange.bind(this)}
onFocus={ () => this.onInputFocus(true) }
onBlur={ () => this.onInputFocus(false) }
value={this.state.input}/>
<br/>
{autoComplete}
</div>
);
}
}
@Eightyplus
Copy link
Author

Replace this.options with this.props.options to use with props set on component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment