react-children-pattern
Version:
React utilities for checking allowed components and retrieving specific children
55 lines (54 loc) • 1.49 kB
JavaScript
import { isArray, isBoolean, isNullish, isNumber, isString, } from "@migudevelop/types-utils";
const UNKNOWN_DISPLAY_NAME = "unknown";
/**
* Determines whether a ReactNode has type property
* @param value Value to check
* @returns boolean
*/
function hasTypeProperty(value) {
return Object.prototype.hasOwnProperty.call(value, "type");
}
/**
* Determines whether a value is a React Element
* @param node Value to check
* @returns boolean
*/
export function isReactElement(node) {
if (isNullish(node) ||
isNumber(node) ||
isString(node) ||
isBoolean(node) ||
isArray(node)) {
return false;
}
return hasTypeProperty(node);
}
/**
*
* @param element dom element
* @returns
*/
export function getReactElementType(element) {
return element?.type;
}
export function getReactElementNodeDisplayName(node) {
if (!isReactElement(node)) {
return UNKNOWN_DISPLAY_NAME;
}
const type = getReactElementType(node);
return isString(type)
? type
: type?.displayName ||
type?.name ||
UNKNOWN_DISPLAY_NAME;
}
export function getReactComponentDisplayName(Component) {
return Component.name;
}
export function findChildrenByType(componentFunction, children) {
if (!children) {
return [];
}
const childrenArray = isArray(children) ? children : [children];
return childrenArray.filter((child) => getReactElementType(child) === componentFunction);
}