Provides a compatibility with React codebases
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Complete React.Children API implementation for working with component children, providing utilities for iteration, counting, and manipulation of child elements.
Maps over children with optional context binding and type safety.
/**
* Maps over children array with optional context binding
* @param children - Array of child elements to map over
* @param fn - Function to apply to each child
* @param ctx - Optional context to bind the function to
* @returns Array of mapped results
*/
map<T, U>(
children: T[],
fn: (child: T, index: number) => U,
ctx?: any
): U[];Usage Examples:
import { Children, createElement } from "inferno-compat";
function ButtonGroup({ children }) {
// Add click handlers to all child buttons
const enhancedChildren = Children.map(children, (child, index) => {
if (child.type === 'button') {
return cloneElement(child, {
onClick: () => console.log(`Button ${index} clicked`),
key: index
});
}
return child;
});
return createElement('div', { className: 'button-group' }, enhancedChildren);
}
// With context binding
function ListRenderer({ children, formatter }) {
const formattedChildren = Children.map(
children,
function(child, index) {
return this.formatChild(child, index);
},
formatter // Context object with formatChild method
);
return createElement('ul', null, formattedChildren);
}
// Handling null/undefined children
function SafeMap({ children }) {
// Children.map gracefully handles null/undefined
const mapped = Children.map(children, (child, index) => {
return createElement('li', { key: index }, child);
});
return createElement('ul', null, mapped || []);
}Iterates over children with side effects, similar to Array.prototype.forEach.
/**
* Iterates over children array with optional context binding
* @param children - Array of child elements to iterate over
* @param fn - Function to call for each child
* @param ctx - Optional context to bind the function to
*/
forEach<T>(
children: T[],
fn: (child: T, index: number) => void,
ctx?: any
): void;Usage Examples:
import { Children, createElement, Component } from "inferno-compat";
class FormValidator extends Component {
constructor(props) {
super(props);
this.state = { errors: [] };
}
validateChildren = () => {
const errors = [];
Children.forEach(this.props.children, (child, index) => {
if (child.type === 'input' && child.props.required && !child.props.value) {
errors.push(`Field ${index + 1} is required`);
}
});
this.setState({ errors });
}
render() {
const { children } = this.props;
const { errors } = this.state;
return createElement('form', null,
children,
errors.length > 0 && createElement('div', { className: 'errors' },
errors.map((error, index) =>
createElement('p', { key: index }, error)
)
)
);
}
}
// Context usage for method binding
class ComponentInspector extends Component {
inspectChild(child, index) {
console.log(`Child ${index}:`, {
type: child.type,
props: Object.keys(child.props || {}),
hasChildren: !!child.children
});
}
componentDidMount() {
Children.forEach(
this.props.children,
this.inspectChild,
this // Bind to component instance
);
}
render() {
return createElement('div', null, this.props.children);
}
}Counts the number of children in a children array.
/**
* Returns the number of children in a children array
* @param children - Array of child elements to count
* @returns Number of children in the array
*/
count(children: any[]): number;Usage Examples:
import { Children, createElement } from "inferno-compat";
function TabContainer({ children, activeTab = 0 }) {
const childCount = Children.count(children);
return createElement('div', { className: 'tab-container' },
// Tab headers
createElement('div', { className: 'tab-headers' },
Array.from({ length: childCount }, (_, index) =>
createElement('button', {
key: index,
className: index === activeTab ? 'active' : '',
onClick: () => setActiveTab(index)
}, `Tab ${index + 1}`)
)
),
// Active tab content
Children.toArray(children)[activeTab]
);
}
function ConditionalRenderer({ children, maxChildren = 5 }) {
const count = Children.count(children);
if (count === 0) {
return createElement('p', null, 'No content available');
}
if (count > maxChildren) {
return createElement('div', null,
createElement('p', null, `Showing first ${maxChildren} of ${count} items`),
Children.toArray(children).slice(0, maxChildren)
);
}
return createElement('div', null, children);
}
// Edge cases handling
function SafeCounter({ children }) {
const count = Children.count(children); // Handles null/undefined gracefully
return createElement('div', null,
createElement('p', null, `Child count: ${count}`),
children
);
}Returns the only child, throwing an error if there are zero or multiple children.
/**
* Returns the single child element, throws error if not exactly one child
* @param children - Children array that should contain exactly one element
* @returns The single child element
* @throws Error if children count is not exactly 1
*/
only(children: any[]): any;Usage Examples:
import { Children, createElement, cloneElement } from "inferno-compat";
function SingleChildWrapper({ children, className }) {
// Ensure exactly one child is provided
const child = Children.only(children);
// Add wrapper class to the single child
return cloneElement(child, {
className: `${child.props.className || ''} ${className}`.trim()
});
}
// Usage - this works
const wrapped = createElement(SingleChildWrapper, { className: 'highlight' },
createElement('p', null, 'Single paragraph')
);
// This would throw an error - multiple children
try {
const invalid = createElement(SingleChildWrapper, { className: 'highlight' },
createElement('p', null, 'First paragraph'),
createElement('p', null, 'Second paragraph')
);
} catch (error) {
console.error(error.message); // "Children.only() expects only one child."
}
function ModalContent({ children }) {
try {
const content = Children.only(children);
return createElement('div', { className: 'modal-content' }, content);
} catch (error) {
return createElement('div', { className: 'modal-error' },
createElement('p', null, 'Modal requires exactly one child element')
);
}
}
// Higher-order component that requires single child
function withEnhancement(WrappedComponent) {
return function EnhancedComponent(props) {
return createElement(WrappedComponent, {
...props,
children: Children.only(props.children) // Ensure single child
});
};
}Converts children to a flattened array, handling nested structures and various input types.
/**
* Converts children to a flattened array
* @param children - Children to convert (can be arrays, single elements, null, etc.)
* @returns Flattened array of children
*/
toArray(children: any[]): any[];Usage Examples:
import { Children, createElement } from "inferno-compat";
function FlexibleList({ children }) {
const childArray = Children.toArray(children);
return createElement('ul', null,
childArray.map((child, index) =>
createElement('li', { key: index }, child)
)
);
}
// Handles various input types
const list = createElement(FlexibleList, null,
'Simple string',
createElement('span', null, 'Element'),
['Nested', 'Array'],
null, // Ignored
undefined, // Ignored
42 // Number
);
function NavigationBreadcrumbs({ children }) {
const items = Children.toArray(children);
return createElement('nav', { className: 'breadcrumbs' },
items.map((item, index) =>
createElement('span', { key: index },
item,
index < items.length - 1 &&
createElement('span', { className: 'separator' }, ' > ')
)
)
);
}
// Complex nesting example
function DeepNestingHandler({ children }) {
const flattened = Children.toArray(children);
console.log('Original structure:', children);
console.log('Flattened array:', flattened);
return createElement('div', null, flattened);
}
const complex = createElement(DeepNestingHandler, null,
[
['deeply', 'nested'],
'array',
[['structure'], 'here']
]
);
// Results in: ['deeply', 'nested', 'array', 'structure', 'here']The complete Children utility object with all methods:
interface Children {
map<T, U>(children: T[], fn: (child: T, index: number) => U, ctx?: any): U[];
forEach<T>(children: T[], fn: (child: T, index: number) => void, ctx?: any): void;
count(children: any[]): number;
only(children: any[]): any;
toArray(children: any[]): any[];
}The Children utilities provide full React compatibility including: