From 851ed2b8b88d7230be2263a6c07c826bf507374d Mon Sep 17 00:00:00 2001 From: Rall3n Date: Tue, 1 Nov 2022 07:16:07 +0100 Subject: [PATCH] Fix focused option if `defaultMenuIsOpen` is set (#5430) --- .changeset/loud-falcons-design.md | 5 +++++ packages/react-select/src/Select.tsx | 17 +++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 .changeset/loud-falcons-design.md 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;