1

ReactProtal interface like this:

interface ReactPortal extends ReactElement {
    key: Key | null;
    children: ReactNode;
}

How can I check if a react element is a react portal?

const element: ReactPortal | JSX.Element = getComponent();
if(isReactPortal(element)) {
   // do something with react portal
} else {
   // do something with usual react element
}

Current solution: check if key property exists

if('key' in element) {
  // is react portal
} else {
  // is usual react element
}

But I am not sure this is strong and safe.

Lin Du
  • 88,126
  • 95
  • 281
  • 483

1 Answers1

4

You can use react-is library to determine if the component is a portal or not. It has many utilities including isPortal function.

If you are more adventurous and want to implement something yourself. You can go through the code here.

Hassaan Tauqir
  • 2,464
  • 1
  • 13
  • 11
  • Nice work man!! I saw the implementation of the `isPortal` function, don't understand why compare with [ReactSymbols](https://github.com/facebook/react/blob/90bde6505e/packages/shared/ReactSymbols.js#L20). But this is another question. – Lin Du Mar 09 '21 at 05:58
  • I got it. Each react element will has `type: Symbol(react.portal)` or `type: Symbol(react.element)` property. Then we can compare with the value of this property. – Lin Du Mar 09 '21 at 06:15