I don't think it's possible to do it using only react-select
api, but you can create own HOC which will add this functionality to AsyncSelect.
class MyAsyncSelect extends React.Component {
/* Select component reference can be used to get currently focused option */
getFocusedOption() {
return this.ref.select.select.state.focusedOption;
}
/* we'll store lastFocusedOption as instance variable (no reason to use state) */
componentDidMount() {
this.lastFocusedOption = this.getFocusedOption();
}
/* Select component reference can be used to check if menu is opened */
isMenuOpen() {
return this.ref.select.state.menuIsOpen;
}
/* This function will be called after each user interaction (click, keydown, mousemove).
If menu is opened and focused value has been changed we will call onFocusedOptionChanged
function passed to this component using props. We do it asynchronously because onKeyDown
event is fired before the focused option has been changed.
*/
onUserInteracted = () => {
Promise.resolve().then(() => {
const focusedOption = this.getFocusedOption();
if (this.isMenuOpen() && this.lastFocusedOption !== focusedOption) {
this.lastFocusedOption = focusedOption;
this.props.onFocusedOptionChanged(focusedOption);
}
});
}
/* in render we're setting onUserInteracted method as callback to different user interactions */
render () {
return (
<div onMouseMove={this.onUserInteracted} onClick={this.onUserInteracted}>
<AsyncSelect
{...this.props}
ref={ref => this.ref = ref}
onKeyDown={this.onUserInteracted}
/>
</div>
);
}
}
Then you can use this custom component in the same way as AsyncSelect
but with ability to react on focused option changes:
class App extends React.Component {
onFocusedOptionChanged = focusedValue => console.log(focusedValue)
render() {
return (
<div>
<MyAsyncSelect
cacheOptions
loadOptions={loadOptions}
defaultOptions
onInputChange={this.handleInputChange}
onFocusedOptionChanged={this.onFocusedOptionChanged}
/>
</div>
);
}
}
working demo: https://stackblitz.com/edit/react-z7izuy
EDIT:
version with additional prop onOptionSelected
which will be called when option is selected by user.
https://stackblitz.com/edit/react-wpljbl