In a React application, I am creating a straightforward autocomplete feature. The code is outlined below.
index.js
import React from 'react';
import { render } from 'react-dom';
import Autocomplete from './Autocomplete';
const styles = {
fontFamily: 'sans-serif',
textAlign: 'left',
};
const items = ['Moscow', 'Ufa', 'Tver', 'Alma ata'];
function onAutoCompleteHandle(val) {
alert(val);
}
const App = () => (
<div style={styles}>
<Autocomplete items={items} onAutocomplete={onAutoCompleteHandle.bind(this)}/>
</div>
);
render(<App />, document.getElementById('root'));
autocomplete.js
Show Suggest Method:
const showSuggest = {
display: this.state.show ? 'block' : 'none',
}
return (
<div>
<input type="text"
className="autoCompleteInput"
onChange={this.handleChange}
ref={input => { this.textInput = input; }}
onClick={this.handleClick}
onKeyPress={this.handleKeyPress}
/>
<span className='suggestWrapper' style={showSuggest}>
<ul className='suggestAutocomplete'>
{this.state.items.map((item, i) => {
return
<li key={i} onClick={this.selectSuggestion}>
{item}
</li>
})}
</ul>
</span>
</div>
)
For a complete working demonstration, visit: https://codesandbox.io/s/react-autocomplete-nbo3n
To reproduce the issue in the provided sandbox example:
-> Click inside the input box.
-> Type a single alphabet such as, a.
-> This will prompt two results: Ufa
, Alma ata
.
-> Press the down arrow key on your keyboard.
Despite attempting to navigate with the keyboard, it is not possible to select any of the dropdown items.
The current functionality only allows for mouse selection, which means that there is a need to incorporate keyboard navigation and selection using keys like the arrow keys and enter key.
Expected Behavior:
-> Users should be able to navigate through the dropdown list using the keyboard.
-> Selecting an item by pressing the enter key should highlight it.
I have attempted assigning
ref={input => { this.textInput = input; }}
to the ul list items suggestAutocomplete
, but this did not resolve the issue.
I have been struggling with this problem for quite some time. Any assistance or modifications to the existing code that enable both mouse and keyboard selection within the autocomplete feature would be greatly appreciated.