add isNode to react-is

This commit is contained in:
Jason Quense 2018-06-27 12:38:51 -04:00
parent 3297102de6
commit efe8e670af
2 changed files with 37 additions and 0 deletions

View File

@ -90,6 +90,23 @@ export function isForwardRef(object: any) {
export function isFragment(object: any) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
export function isNode(object: any) {
switch (typeof object) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !object;
case 'object':
if (Array.isArray(object)) {
return object.every(isNode);
}
return object === null || isElement(object);
default:
return false;
}
}
export function isProfiler(object: any) {
return typeOf(object) === REACT_PROFILER_TYPE;
}

View File

@ -85,6 +85,26 @@ describe('ReactIs', () => {
expect(ReactIs.isContextConsumer(<div />)).toBe(false);
});
it('should identify nodes', () => {
expect(ReactIs.isNode(<div />)).toBe(true);
expect(ReactIs.isNode('div')).toBe(true);
expect(ReactIs.isNode(false)).toBe(true);
expect(ReactIs.isNode(true)).toBe(false);
expect(ReactIs.isNode(123)).toBe(true);
expect(ReactIs.isNode(null)).toBe(true);
expect(ReactIs.isNode(undefined)).toBe(true);
expect(ReactIs.isNode([1, 'string', <div />])).toBe(true);
expect(ReactIs.isNode({})).toBe(false);
// It should also identify more specific types as nodes
const Context = React.createContext(false);
expect(ReactIs.isNode(<Context.Provider />)).toBe(true);
expect(ReactIs.isNode(<Context.Consumer />)).toBe(true);
expect(ReactIs.isNode(<React.Fragment />)).toBe(true);
expect(ReactIs.isNode(<React.unstable_AsyncMode />)).toBe(true);
expect(ReactIs.isNode(<React.StrictMode />)).toBe(true);
});
it('should identify context providers', () => {
const Context = React.createContext(false);
expect(ReactIs.typeOf(<Context.Provider />)).toBe(ReactIs.ContextProvider);