Check if a child is React.Fragment

11.6k Views Asked by At

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;
  }
};
2

There are 2 best solutions below

0
On

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
0
On

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.