Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a child is React.Fragment

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;
  }
};
like image 675
Dmitry Druganov Avatar asked Feb 27 '18 15:02

Dmitry Druganov


People also ask

Is React fragment same as <>?

<> 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.

Is React fragment a div?

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.

What type is React fragment?

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.

What is a React fragment?

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.


2 Answers

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.

like image 194
Lukas Avatar answered Oct 28 '22 06:10

Lukas


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
like image 34
kraf Avatar answered Oct 28 '22 04:10

kraf