Check if child renders top-level React Fragment

500 Views Asked by At

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.

0

There are 0 best solutions below