user17824073
user17824073

Reputation:

How to place React Select Menu

I have the following example that I'm trying to fix in my project. So page-wrapper's height is supposed to emulate a page that has some content on it, hence the height CSS property. I placed select-container in the middle intentionally to have space both above and below it. If I open the menu for example when I land on the page, so no scroll in yet, instead of opening it up top, ReactSelect is opening it at the bottom and scrolling me down to it. I tried menuPlacement = "auto" prop as you can see because from what I've seen in the documentation, it should do the positioning automatically, but it doesn't seem to work.

My Component

import ReactSelect from "react-select";

const options = [
  { label: "No 1", value: "test_1" },
  { label: "No 2", value: "test_2" },
  { label: "No 3", value: "test_3" },
  { label: "No 4", value: "test_4" }
];

export default function App() {
  return (
    <div className="page-wrapper">
      <div className="select-container">
        <ReactSelect options={options} menuPlacement="auto" />
      </div>
    </div>
  );
}

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.page-wrapper {
  min-height: 180vh;
  width: 100%;
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
}

.select-container {
  width: 90%;
  margin: 0 auto;
}

I have a Sandbox code here if needed.

Upvotes: 4

Views: 15678

Answers (1)

Emanuele Scarabattoli
Emanuele Scarabattoli

Reputation: 4489

Well, even if this options seems to be not so clear, it actually fixes the issue:

<ReactSelect menuPosition="fixed" options={options} menuPlacement="auto" />

By the way, read carefully here about the implications:

https://react-select.com/props

menuPosition property documentation.

With absolute, as per default (and not enough space after the input):

enter image description here

With fixed (and not enough space after the input):

enter image description here

If there is enough space after the input, menu is rendered after the input.

Explanation

Seems that the menuPosition decide how the menu should be considered "out-of-space", similar to CSS, in some way. If absolute, it refers to the space available in the parent container (that, in your case, since the height is 180vh, according to the code you shared, is enough, unless you resize the page to make it smaller), if fixed, it refers to the space available in the visible part of the screen.

Edit

After reading the comments to this answer, even if I think that, in my opinion, this solution is over-complication something potentially not so relevant from an UX point of view, a possible fix is the following:

<ReactSelect options={options} menuPlacement={shouldBePlacedOnTopInstead ? "top" : "auto"} />

with shouldBePlacedOnTopInstead state computed using window scroll and visible screen related properties.

Upvotes: 11

Related Questions