Search code examples
javascriptreactjsreact-selectreact-window

How to fix react-window height issue with react-select?


I'm using react-select with react-window but there is issue with height of dropdown like:

I have only two value but height is larger than items, how can I fix it? dropdown values coming from API that can be vary.

Note: I also need to define maxHeight of dropdown.

Code:

import Select from "react-select";
import { FixedSizeList as List } from "react-window";

const CustomMenuList = (props) => {
  const itemHeight = 35;
  const { options, children, maxHeight, getValue } = props;
  const [value] = getValue();
  const initialOffset = options.indexOf(value) * itemHeight;

  return (
    <div>
      <List
        style={{ height: "max-content", maxHeight: maxHeight }}
        height={maxHeight}
        itemCount={children.length}
        itemSize={itemHeight}
        initialScrollOffset={initialOffset}
      >
        {({ index, style }) => <div style={style}>{children[index]}</div>}
      </List>
    </div>
  );
};

const options = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" }
];

const ReactSelect = () => {
  return (
    <>
      <Select
        options={options}
        components={{
          MenuList: CustomMenuList
        }}
      />
    </>
  );
};

export default ReactSelect;

Code Sandbox


Solution

  • Changing the height using react style to max-content fixes the issue here

      <List
        style={{ height: "max-content", maxHeight: maxHeight }}
        height={1}
        itemCount={children.length}
        itemSize={itemHeight}
        initialScrollOffset={initialOffset}
      >
        {({ index, style }) => <div style={style}>{children[index]}</div>}
      </List>
    

    you still need to specify height since the component requires it but it can be any value the max-content will overwrite it. This is a fixed fork of your issue