Component APIs

children

Edit this page

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>
);
}

Report an issue with this page