React open dropDown on top or bottom of dropDown input based on the element's position

Viewed 112

I have a DropDown component. Currently, on click, the list will open on the bottom of the input box to the max height of 200px.

enter image description here

The problem is that if the input box is at the bottom of the page, the list will go down the screen and needs to scroll to be seen. I want the list to open on top of the input box if there is not enough space at the bottom of the box and the bottom of the screen.

the problem :

enter image description here

the desired result:

enter image description here

1 Answers

Maybe you looking for getBoundingClientRect property It will return the element position based on the current viewport

<!DOCTYPE html>
<html>
<h1>The Element Object</h1>
<h2>The getBoundingClientRect() Method</h2>

<body>
<div onscroll="myFunction()" style="height:200px; width:300px; overflow:auto;">
<div id="myDiv" style="width:250px; height:150px; padding:16px; border:1px solid black;">
Scroll to display the bounding client rect of the element with the border.
</div>
<div style="width:1000px; height:1000px;"></div>
</div>
<p id="demo"></p>

<script>
function myFunction() {
  const element = document.getElementById("myDiv");
  const rect = element.getBoundingClientRect();

  document.getElementById("demo").innerHTML =
"Left: " + rect.left.toFixed() + ", Top: " + rect.top.toFixed() + ", Width: " + rect.width + ", Height: " + rect.height;
}
</script>

</body>
</html>

Related