Skip to content

Latest commit

 

History

History
105 lines (79 loc) · 2.05 KB

File metadata and controls

105 lines (79 loc) · 2.05 KB
title children
use_cases resolving component children, normalizing JSX children, slot-like helpers, interacting with child content in library components
tags
components
children
jsx
utilities
version 1.0
description Resolve a component's `children` prop into a stable accessor.

children resolves a component's children prop and returns a stable accessor for the resolved result.

Import

import { children } from "solid-js";

Type

type ResolvedJSXElement = Exclude<JSX.Element, JSX.ArrayElement>;
type ResolvedChildren = ResolvedJSXElement | ResolvedJSXElement[];

function children(fn: Accessor<JSX.Element>): Accessor<ResolvedChildren> & {
	toArray: () => ResolvedJSXElement[];
};

Parameters

fn

  • Type: () => JSX.Element
  • Required: Yes

Accessor that returns the component's children value.

Return value

  • Type: Accessor<ResolvedChildren> & { toArray: () => ResolvedJSXElement[] }

Returns an accessor for the resolved children. The accessor also exposes toArray().

Behavior

  • The returned accessor memoizes the resolved children, so repeated reads use the resolved result instead of recreating the child structure.
  • children resolves nested arrays, fragments, and zero-argument child accessors from props.children.
  • toArray() returns the resolved children as an array. It returns [] when the resolved value is null or undefined.

Examples

Basic usage

function Wrapper(props) {
	const resolved = children(() => props.children);

	return <div>{resolved()}</div>;
}

function Example() {
	return (
		<Wrapper>
			<span>First</span>
			<span>Second</span>
		</Wrapper>
	);
}

Flatten children into an array

function List(props) {
	const resolved = children(() => props.children);

	return (
		<ul>
			{resolved.toArray().map((child) => (
				<li>{child}</li>
			))}
		</ul>
	);
}

function Example() {
	return (
		<List>
			<span>Alpha</span>
			<span>Beta</span>
		</List>
	);
}

Related