Reputation: 21
I'm developing an autocomplete component, but I'm not able to scroll with the arrow keys (down/up), with the mouse it works normally.
I've researched a lot about it and tried to solve this problem with refs, but it didn't work.
const refs = filteredSuggestions.reduce((acc, value) => {
acc[value.id] = React.createRef();
return acc;
}, {});
Place where it is referenced
suggestionsListComponent = (
<ul class="suggestions">
{filteredSuggestions.map((suggestion, index) => {
let className;
if (index === activeSuggestion) {
className = "suggestion-active";
}
return (
<li ref={refs[suggestion.id]} className={className} key={suggestion} onClick={onClick}>
{suggestion}
</li>
);
})}
</ul>
);
The complete code is here: codesandbox
Can anyone help me solve this problem?
Upvotes: 2
Views: 5422
Reputation: 1913
Easily integrate your react component with keyboard arrow keys, with the same configuration used in swipe-react and wheel-react packages.
Usage
Install the npm package:
npm install --save arrow-keys-react
Import it:
import ArrowKeysReact from 'arrow-keys-react';
Config arrow keys events ('left', 'right', 'up', 'down'), at least one of them, in your component constructor, or in render function:
ArrowKeysReact.config({
left: () => {
console.log('left key detected.');
},
right: () => {
console.log('right key detected.');
},
up: () => {
console.log('up key detected.');
},
down: () => {
console.log('down key detected.');
}
});
4.Integrate with your React component:
<YourComponent {...ArrowKeysReact.events} />
Example
import React, { Component } from 'react';
import ArrowKeysReact from 'arrow-keys-react';
class App extends Component {
constructor(props){
super(props);
this.state = {
content: 'Use arrow keys on your keyboard!'
};
ArrowKeysReact.config({
left: () => {
this.setState({
content: 'left key detected.'
});
},
right: () => {
this.setState({
content: 'right key detected.'
});
},
up: () => {
this.setState({
content: 'up key detected.'
});
},
down: () => {
this.setState({
content: 'down key detected.'
});
}
});
}
render() {
return (
<div {...ArrowKeysReact.events} tabIndex="1">
{this.state.content}
</div>
);
}
}
export default App;
Remarks
div
, add tabIndex
property.focus()
when it loaded.ArrowKeysReact.config
can be placed in render
function instead of in the constructor
function.Upvotes: 1