2

Is there a way to programmatically check if a React Element returns a top-level React.Fragment component? For most use cases, react-is is the recommended way to check this type of behavior, but it does not work in this case. If a function component returns a top-level fragment, it should be wrapped in a div element; otherwise, it should render the component as normal. Perhaps this is a limitation of the react-is library.

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

// Component is unable to be changed. Component data is coming from the server.
const TopLevelFragment = () => (
  <>
    <div>Child 1</div>
    <div>child 2</div>
  </>
);

console.log(ReactIs.isFragment(<></>)); // true
console.log(ReactIs.typeOf(<></>) === ReactIs.Fragment); // true

// I want to know if an FC will render a top-level fragment.
console.log(ReactIs.isFragment(TopLevelFragment)) // false!!

Here is a code sandbox for the above snippet: sandbox link

Ideal usage:

export const App: React.FC<{ children?: React.ReactNode }> = ({ children }) => {
    return (
        <div className='mx-auto grid gap-4'>
            {React.Children.map(children, (child, index) => {
                // Here is where the isFragment call work correctly return true
                const Parent = ReactIs.isFragment(child) ? 'div' : React.Fragment;
                return <Parent key={index}>{child}</Parent>;
            })}
        </div>
    );
};

This is a related question and answer that did not solve my issue.

vsync
  • 118,978
  • 58
  • 307
  • 400
  • `ReactIs.isFragment(TopLevelFragment)` is presumably false because it isn't a fragment, it's a custom component (with a fragment as its child). Is there a way you can extract the child from a component? Checking if it's child is a fragment using `isFragment` should work. – Nathan Oct 17 '22 at 19:26
  • Because the TopLevelFragment is a custom component will a fragment as its child, the props.children of that custom component are the two divs since the TopLevelFragment function has already been rendered. Is there a way to access the grandchildren before they are rendered? Thanks! – Charles Kornoelje Oct 17 '22 at 19:45
  • 1
    You unfortunately need to render your component first, since `TopLevelFragment` returns a component and not the rendered output. This would work: `console.log(ReactIs.isFragment(TopLevelFragment()));` – Terry Jan 09 '23 at 14:36

0 Answers0