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;
}
};
<> is the shorthand tag for React. Fragment which allows us to group a list of elements without wrapping them in a new node. The only difference between them is that the shorthand version does not support the key attribute.
React Fragment vs divReact Fragment is a component exposed by React which serves as a parent component in JSX but doesn't add anything to the DOM. The div element on the other hand is an HTML element with no semantic meaning but when used, will be added to the DOM as a node.
A React Fragment is an empty React Element that can be used to group elements and components together in React to keep the validity of HTML and without adding the additional noise of itself to the end result of the DOM.
A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With