Created
June 15, 2018 08:08
-
-
Save Eightyplus/63aba24abf1db13f79cf5793e20129b5 to your computer and use it in GitHub Desktop.
React auto-complete input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replace this.options with this.props.options to use with props set on component.