3

I'm building a component in StencilJS which has a tooltip.

I would like to append this tooltip's markup in the document.body instead of my component, as it runs into issues when the component is wrapped in an element with overflow:hidden (the tooltip gets cut off)

Is there any way to achieve this?

I have the exact same component in React, and I managed to fix it by using ReactDOM.createPortal(tooltip, document.body) but I can't seem to be able to find a similar solution in Stencil (plus, the documentation is quite basic).

I also tried manually generating the elements with document.createElement but it's a pain and too verbose, and I have a couple of icons as components I would like to include.

An alternative solution would be a way to transform JSX into actual markup I can then use by doing document.body.append(tooltip).

janarvaez
  • 33
  • 4

1 Answers1

5

createElement is probably the easiest and most flexible way.

Ionic does this when creating overlays (alerts, modals, popovers etc.).

const tooltip = document.createElement('my-tooltip');
tooltip.content = 'Tooltip Content <my-icon name="foo"/>';
document.body.append(tooltip);

This way you can easily pass properties to tooltip, including where the tooltip should be positioned (example in Ionic's popover component).

Instead of passing the HTML as a property (and using it via <div innerHTML={this.content}>) you can also pass the name of a component to be included which the tooltip then creates with createElement.

Thomas
  • 8,426
  • 1
  • 25
  • 49
  • Awesome thanks! I guess if this is the way Ionic is doing it, it should be the way forward. Also, I forgot I could do `document.createElement` on a custom component :facepalm: – janarvaez Jul 24 '20 at 09:32