Reputation: 2348
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;
}
};
Upvotes: 28
Views: 13052
Reputation: 9
function isFragment(NodeType) {
const isSymbol = typeof NodeType === 'symbol'
if (isSymbol && NodeType.toString() === 'Symbol(react.fragment)') {
return true
}
return false
}
Upvotes: 0
Reputation: 1309
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
Upvotes: 17
Reputation: 10340
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.
Upvotes: 18