@jsdevlab/react-headless
v1.1.1
Published
Type-safe headless logic components for React 19.
Maintainers
Readme
@jsdevlab/react-headless
Type-safe headless logic components for React 19. Every component is style-free, renders no wrapper DOM of its own, and works in both client and server components.
Installation
pnpm add @jsdevlab/react-headless react react-domReact 19 and React DOM 19 are peer dependencies. React DOM is used by
Portal.
Components
For
Render a list and infer the item type from each.
import { For } from '@jsdevlab/react-headless';
<For
each={users}
keyBy={(user) => user.id}
filter={(user) => user.active}
fallback={<Empty />}
>
{(user, index) => <UserRow user={user} index={index} />}
</For>;each— a readonly array of items.children—(item, index) => ReactNode.filter— optional predicate.fallbackis rendered when the filtered list is empty.fallback— rendered when the list is empty.keyBy— derives a stable React key. Defaults to the item index.
For wraps each item in a keyed fragment and renders no DOM of its own.
Repeat / Range
import { Range, Repeat } from '@jsdevlab/react-headless';
<Repeat times={3}>{(index) => <Skeleton key={index} />}</Repeat>;
<Range from={1} to={5} step={1}>
{(value) => <Dot key={value} />}
</Range>;Repeatrenders childrentimestimes with a zero-based index. Non-finite and non-positive values renderfallback.Rangerenders values fromfrom(inclusive) toto(exclusive). A negativestepiterates downwards; empty or invalid ranges renderfallback.
Show / When / Unless / Not
import { Not, Show, Unless, When } from '@jsdevlab/react-headless';
<Show when={isLoading} fallback={<Content />}>
<Spinner />
</Show>;
<When when={() => permissions.canEdit}>
<Editor />
</When>;
<Unless when={isLoading}>
<Content />
</Unless>;
<Not condition={isLoading} fallback={<Content />}>
<Spinner />
</Not>;- A condition can be a boolean or a lazy
() => booleanfunction. childrenandfallbackaccept either aReactNodeor a lazy render function.Whenis an alias ofShow.Unlessrenders its children when the condition is false.Notis a convenience wrapper aroundUnless.
With
import { With } from '@jsdevlab/react-headless';
<With value={user} fallback={<SignIn />}>
{(user) => <Profile user={user} />}
</With>;With renders its children when value is present and narrows the value type
for the render function. false, null, and undefined are absent; 0 and
'' are present.
Every / Some / None
import { Every, None, Some } from '@jsdevlab/react-headless';
<Every conditions={[isReady, () => permissions.canEdit]}>
<Editor />
</Every>;
<Some conditions={[isAdmin, isOwner]} fallback={<ReadOnly />}>
<Toolbar />
</Some>;
<None conditions={[isLoading, hasError]} fallback={<Spinner />}>
<Content />
</None>;- Each condition can be a boolean or a lazy
() => booleanfunction. Everyrequires all conditions to be true.Somerequires at least one condition to be true.Nonerequires all conditions to be false.
Switch / Case / Default
import { Case, Default, Switch } from '@jsdevlab/react-headless';
<Switch value={status} fallback={<Unknown />}>
<Case value="loading">
<Spinner />
</Case>
<Case value={['ready', 'idle']}>
<Content />
</Case>
<Case value={(value) => value.startsWith('error')}>
{(value) => <ErrorView code={value} />}
</Case>
<Default>
<Empty />
</Default>
</Switch>;SwitchmatchesCasebranches againstvalueusingObject.is.- A
Casevalue can be a single value, an array of values, or a predicate function(value) => boolean. Casechildren andDefaultchildren can be render functions.Caserender functions receive the switch value.- The first matching case wins.
Defaultis used when no case matches.fallbackis used when there is no match and noDefault. multiplerenders every matching case instead of only the first.CaseandDefaultare markers and render nothing when used outside aSwitch.
Typed switches with createSwitch
Switch and Case are generic, but TypeScript does not propagate a parent
component's type parameters to nested JSX children. Use createSwitch<T>() to
bind both components to the same type:
import { createSwitch } from '@jsdevlab/react-headless';
const {
Switch: StatusSwitch,
Case: StatusCase,
Default: StatusDefault,
} = createSwitch<'active' | 'idle' | 'error'>();
<StatusSwitch value={status}>
<StatusCase value="active">
<Active />
</StatusCase>
<StatusCase value={['idle', 'error']}>
<Inactive />
</StatusCase>
<StatusDefault>
<Unknown />
</StatusDefault>
</StatusSwitch>;Both StatusSwitch value and StatusCase value are checked against
'active' | 'idle' | 'error'.
Await / Catch
import { Await, Catch } from '@jsdevlab/react-headless';
<Await
promise={userPromise}
fallback={<Spinner />}
error={(error, reset) => (
<ErrorView error={error} onRetry={reset} />
)}
onError={(error) => report(error)}
>
{(user) => <Profile user={user} />}
</Await>;
<Catch
fallback={(error, reset) => (
<ErrorView error={error} onRetry={reset} />
)}
resetKeys={[userId]}
>
<Profile />
</Catch>;Awaitreads a stable promise with React'suseAPI. Pending rendersfallback; rejected promises rendererrorwhen provided, otherwise they propagate to the nearest error boundary.Catchis a headless error boundary. It catches render and lifecycle errors, not errors thrown in event handlers or async code. ChangingresetKeysresets the boundary.- Both are client components marked with
'use client'.
Portal
import { Portal } from '@jsdevlab/react-headless';
const containerRef = useRef<HTMLDivElement>(null);
<Portal container={containerRef}>
<Modal />
</Portal>;containeraccepts an element, a document fragment, a ref object, ornull. It defaults todocument.body;nullrenders nothing.disabledrenders children inline instead of portaling.Portalrenders nothing on the server and portals after mounting on the client. It is a client component marked with'use client'.
Type safety
Forinfers its item type fromeach.Withnarrows awayfalse,null, andundefined.Awaitinfers the resolved promise value.createSwitch<T>()shares one type parameter betweenSwitchandCase.- Conditions accept
boolean | (() => boolean). - Lists and condition arrays are readonly.
Server components
For, Show / When / Unless / Not, With, Repeat / Range,
Every / Some / None, and Switch / Case / Default use no hooks or
browser APIs and can be used in React Server Components.
Await, Catch, and Portal are client components and are marked with
'use client'.
License
MIT
