Skip to content

Commit

Permalink
feature: support isFragment (#4042)
Browse files Browse the repository at this point in the history
* feat: support isFragment

* feat: add unit test

* feat: CR fixed

---------

Co-authored-by: bobihuang <[email protected]>
Co-authored-by: Jovi De Croock <[email protected]>
  • Loading branch information
3 people committed Aug 3, 2023
1 parent c294e8b commit d8f2fb3
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
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);
});
});

0 comments on commit d8f2fb3

Please sign in to comment.