Dynamically updating the option list rests the focus to the first element.
Dynamically updating the options list resets the focus to the first element. Even though the options are the same (same value), just a new object reference.
In my use case, this happens because the select controls a filter and the results change when selecting options. The filter options have the count (facet filtering) of the results associated with the filter option in their label. So when updating the results we also update the options to update the counts. This means that selecting an option with the keyboard triggers an update of the results, which leads to the recomputation of the options and shortly after the focus is set to the first option in the results list.
This makes keyboard usage very annoying.
This is a v5 bug: https://codesandbox.io/s/react-select-v5-sandbox-forked-s58hcn?file=/example.js
Hi @MoritzKn, I am currently encountering the same issue.
Did you have any workaround?
Unfortunately not. Can’t really think of any workaround for this either.
@jcorevnue2022 actually, I found a (very hacky) workaround:
/**
* Workaround for React Select issue "Dynamically updating the option list rests the focus to the first element"
*
* See: https://github.com/JedWatson/react-select/issues/5367
*/
function useFixReactSelectFocus<Option extends { value: string }>(
selectRef: RefObject<SelectClass<Option, true>>,
options: Option[]
) {
// HACK: This accesses the select class via a ref
const select = selectRef.current;
if (select && select.state.focusedOption) {
const focusedOptionValue = select.state.focusedOption.value;
const focusedOption =
options.find((o) => o.value === focusedOptionValue) || null;
// HACK: manipulating the state without setState is evil (but needed here as we are mid-transition)
select.state.focusedOption = focusedOption;
}
}
Then in your component:
import { useRef } from "react";
import type SelectClass from "react-select/dist/declarations/src/Select";
function MyComponent() {
const selectRef = useRef<SelectClass<FilterOption, true>>(null);
// [...]
useFixReactSelectFocus(selectRef, options);
return (
<Component
selectRef={selectRef}
options={options}
/>
);
}
@MoritzKn would it be rather ref={selectRef} instead of selectRef={selectRef} ?
@linaia yep, I guess so
I am having the same problem here. I was just wondering if similar solution as react-table uses would work here. They have the skipPageReset-option that keeps the page from resetting when data changes. This could be turned on before starting to fetch data and turned back on after the fetch.
is there any plan to fix this? I see this bug has been open for very long time?