0

Issue: Arrow Key Scrolling Not Working in react-select with react-window I am experiencing an issue where I am unable to scroll through the react-select dropdown list using the up and down arrow keys when implementing react-window for virtualization. However, scrolling works correctly when react-window is not used.

Code Snippet: MenuList with Virtualization

const MenuList = React.memo(({ options, children, maxHeight, getValue }) => {
  const [value] = getValue();
  const height = Math.min(children.length * 40, maxHeight);
  const initialOffset = options.indexOf(value) * 40;

  return (
    <List
      height={options.length >= 8 ? maxHeight : height}
      itemCount={children.length}
      itemSize={40}
      initialScrollOffset={initialOffset}
      width="100%"
    >
      {({ index, style }) => <div style={style}>{children[index]}</div>}
    </List>
  );
});

enter image description here

enter image description here

1 Answer 1

0
import React, { useRef } from "react";
import Select, { components } from "react-select";
import { FixedSizeList as List } from "react-window";

// Sample options for the dropdown
const options = [
  { value: "apple", label: "Apple" },
  { value: "banana", label: "Banana" },
  { value: "orange", label: "Orange" },
  { value: "grape", label: "Grape" },
  // Add more options to test scrolling and virtualization
];

// Custom MenuList component using react-window
const MenuList = (props) => {
  const { options, children, maxHeight, getValue } = props;
  const height = 35; // Height of each option
  const [value] = getValue();
  const initialOffset = options.findIndex(
    (option) => option.value === value?.value
  );

  // Reference for list to manage scrolling
  const listRef = useRef();

  return (
    <List
      height={maxHeight} // Set the height of the dropdown
      itemCount={children.length} // Number of items to display
      itemSize={height} // Height of each item
      initialScrollOffset={initialOffset * height} // Scroll to the selected value
      ref={listRef}
    >
      {({ index, style }) => (
        <div style={style}>
          {children[index]} {/* Render each option */}
        </div>
      )}
    </List>
  );
};

const CustomSelect = () => (
  <Select
    options={options} // Pass your options
    components={{ MenuList }} // Override the MenuList component
  />
);

export default CustomSelect;


Try this way.
Sign up to request clarification or add additional context in comments.

1 Comment

Not working! may be accessibility issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.