25

As I see React.isFragment is only a proposal for the moment: https://github.com/facebook/react/issues/12038

Is there a workaround to do something like

if (child instanceof React.Fragment) {
  ...
}

until that API is available.

Temporary solution that works for me:

const isReactFragment = child => {
  try {
    return child.type.toString() === React.Fragment.toString();
  } catch (e) {
    return false;
  }
};
Dmitry Druganov
  • 2,088
  • 3
  • 23
  • 32
  • 1
    Are you sure it is not available? According to this comment you can try out the package (though an alpha version) already: https://github.com/facebook/react/issues/12038#issuecomment-365023560 – Niekert Feb 27 '18 at 16:12
  • 2
    @Niekert You are right, it should be available through `react-is` package, which is alpha right now. – Dmitry Druganov Feb 27 '18 at 16:30

2 Answers2

15

For completeness sake the package react-is is now the recommended way to go as mentioned in the closing message of the above issue.

Use like this:

import React from "react";
import * as ReactIs from 'react-is';

ReactIs.isFragment(<></>); // true
ReactIs.typeOf(<></>) === ReactIs.Fragment; // true
kraf
  • 1,269
  • 12
  • 21
14

Nowadays, this is possible:

function isReactFragment(variableToInspect) {
  if (variableToInspect.type) {
    return variableToInspect.type === React.Fragment;
  }
  return variableToInspect === React.Fragment;
}

The check for variableToInspect.type is because component instances have that property.

Lukas
  • 9,752
  • 15
  • 76
  • 120