How to position tooltip in react portal?

Viewed 2363

I am using React Portal to create tooltip. I would like to make button's bottom adjacent to tooltip's top and they align with each other by right side.

If I do not use portal, I can use absolute/relative to position tooltip corresponding to button. But portal will make these two elements not knowing each other, so I need to call getBoundingClientRect to get position of button and calculate tooltip's position.

Then how can I set style object for tooltip to achieve this?

BTW, the content's size is dynamic, width ranging from 100px to 200px and height ranging from 50px to 150px. I hope not to use hardcoded value for them.

UPDATE

Please do not ask me why I do not choose this library or that library. I have stated the solution by those libraries as long as I do not use react portal.

Please take time to read official react portal documentation, which explains enough about the scenario when your tooltip is placed inside DOM hierarchy and it will be covered or overlapped by other elements due to z-index of parent container. Therefore, I choose to use react portal to place it under a root node in top level.

const button = document.getElementById('button');
const buttonRect = button.getBoundingClientRect();
const tooltip = document.getElementById('tooltip');
// tooltip.style.? = ?


//           |------|
//           |button|
//           |------|
//    |-------------|
//    |             |
//    |   tooltip   |
//    |             |
//    |-------------|
#app-root {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #999;
  display: flex;
  justify-content: center;
  align-items: center;
}

#portal-root {
  position: fixed;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
}

.content {
  width: 200px;
  height: 100px;
  background-color: #000;
}
<div id="app-root">
  <button id="button">button</button>
</div>
<div id="portal-root">
  <div id="tooltip">
    <div class="content"><div>
  </div>
</div>

1 Answers

Is that what you want to achieve?

const button = document.getElementById('button');
const buttonRect = button.getBoundingClientRect();
const tooltip = document.getElementById('tooltip');
// tooltip.style.? = ?


//           |------|
//           |button|
//           |------|
//    |-------------|
//    |             |
//    |   tooltip   |
//    |             |
//    |-------------|
#app-root {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #999;
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
}

#portal-root {
  position: relative;
}

.content {
  width: 200px;
  height: 100px;
  background-color: #000;
}
<div id="app-root">
  <button id="button">button</button>
  <div id="portal-root">
  <div id="tooltip">
    <div class="content"><div>
  </div>
</div>
</div>

Related