Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: support isFragment #4042

Merged
merged 6 commits into from
Aug 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions compat/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ declare namespace React {
...children: preact.ComponentChildren[]
) => preact.VNode<any>;
export function isValidElement(element: any): boolean;
export function isFragment(element: any): boolean;
export function findDOMNode(
component: preact.Component | Element
): Element | null;
Expand Down
11 changes: 11 additions & 0 deletions compat/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ function isValidElement(element) {
return !!element && element.$$typeof === REACT_ELEMENT_TYPE;
}

/**
* Check if the passed element is a Fragment node.
* @param {*} element The element to check
* @returns {boolean}
*/
function isFragment(element) {
return isValidElement(element) && element.type === Fragment;
}

/**
* Wrap `cloneElement` to abort if the passed element is not a valid element and apply
* all vnode normalizations.
Expand Down Expand Up @@ -185,6 +194,7 @@ export {
createRef,
Fragment,
isValidElement,
isFragment,
findDOMNode,
Component,
PureComponent,
Expand Down Expand Up @@ -231,6 +241,7 @@ export default {
createRef,
Fragment,
isValidElement,
isFragment,
findDOMNode,
Component,
PureComponent,
Expand Down
22 changes: 22 additions & 0 deletions compat/test/browser/isFragment.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createElement as preactCreateElement, Fragment } from 'preact';
import React, { isFragment } from 'preact/compat';

describe('isFragment', () => {
it('should check return false for invalid arguments', () => {
expect(isFragment(null)).to.equal(false);
expect(isFragment(false)).to.equal(false);
expect(isFragment(true)).to.equal(false);
expect(isFragment('foo')).to.equal(false);
expect(isFragment(123)).to.equal(false);
expect(isFragment([])).to.equal(false);
expect(isFragment({})).to.equal(false);
});

it('should detect a preact vnode', () => {
expect(isFragment(preactCreateElement(Fragment, {}))).to.equal(true);
});

it('should detect a compat vnode', () => {
expect(isFragment(React.createElement(Fragment, {}))).to.equal(true);
});
});