diff --git a/.changeset/loud-falcons-design.md b/.changeset/loud-falcons-design.md new file mode 100644 index 0000000000..ff44b7e67e --- /dev/null +++ b/.changeset/loud-falcons-design.md @@ -0,0 +1,5 @@ +--- +'react-select': patch +--- + +Fix focused option if `defaultMenuIsOpen` is set diff --git a/packages/react-select/src/Select.tsx b/packages/react-select/src/Select.tsx index 699f6119ce..30e67458b3 100644 --- a/packages/react-select/src/Select.tsx +++ b/packages/react-select/src/Select.tsx @@ -623,6 +623,13 @@ export default class Select< this.instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId); this.state.selectValue = cleanValue(props.value); + + // Set focusedOption if menuIsOpen is set on init (e.g. defaultMenuIsOpen) + if (props.menuIsOpen && this.state.selectValue.length) { + const focusableOptions = this.buildFocusableOptions(); + const optionIndex = focusableOptions.indexOf(this.state.selectValue[0]); + this.state.focusedOption = focusableOptions[optionIndex]; + } } static getDerivedStateFromProps( @@ -712,6 +719,16 @@ export default class Select< if (this.props.autoFocus) { this.focusInput(); } + + // Scroll focusedOption into view if menuIsOpen is set on mount (e.g. defaultMenuIsOpen) + if ( + this.props.menuIsOpen && + this.state.focusedOption && + this.menuListRef && + this.focusedOptionRef + ) { + scrollIntoView(this.menuListRef, this.focusedOptionRef); + } } componentDidUpdate(prevProps: Props) { const { isDisabled, menuIsOpen } = this.props;