Skip to content

Commit

Permalink
Merge pull request #175 from appfolio/fixSelectFocusIssue
Browse files Browse the repository at this point in the history
Fix react-select focus issue
  • Loading branch information
gthomas-appfolio authored Mar 17, 2017
2 parents cc0143b + c761327 commit 4652583
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/components/Select.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,49 @@ import over from 'lodash.over';
// Disables CSS modules to import as global:
import './Select.scss';

/**
* This is a workaround for a current bug in react-select where the currently focused item is not
* highlighted after updating the options list.
*
* This can be removed when a new version of react-select is released with this PR merged:
* https://github.com/JedWatson/react-select/pull/1512
* https://github.com/JedWatson/react-select/issues/1513
* https://github.com/JedWatson/react-select/issues/1565
*/
function monkeyPatchReactSelectGetFocusableOptionIndex(element) {
if (!element) {
return;
}

// eslint-disable-next-line no-param-reassign
element.getFocusableOptionIndex = function getFocusableOptionIndex(selectedOption) {
// eslint-disable-next-line no-underscore-dangle
const options = this._visibleOptions;
if (!options.length) return null;

// eslint-disable-next-line prefer-const
let focusedOption = this.state.focusedOption || selectedOption;
if (focusedOption && !focusedOption.disabled) {
let focusedOptionIndex = -1;
options.some((option, index) => {
const isOptionEqual = option.value === focusedOption.value;
if (isOptionEqual) {
focusedOptionIndex = index;
}
return isOptionEqual;
});
if (focusedOptionIndex !== -1) {
return focusedOptionIndex;
}
}

for (let i = 0; i < options.length; i++) {
if (!options[i].disabled) return i;
}
return null;
};
}

class Select extends Component {
static propTypes = {
defaultValue: React.PropTypes.any,
Expand Down Expand Up @@ -38,6 +81,7 @@ class Select extends Component {
onChange={over([this.updateValue, onChange])}
value={value || this.state.value}
{...props}
ref={element => { monkeyPatchReactSelectGetFocusableOptionIndex(element); }}
/>
);
}
Expand Down

0 comments on commit 4652583

Please sign in to comment.