Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/components/For.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,20 @@ export type ForProps<T> = {
children: (item: T, index: number) => React.ReactNode;
};

/**
* Renders a list by mapping each item to JSX with a render function.
*
* @example
* ```tsx
* <For each={users}>
* {(user, index) => (
* <li key={user.id}>
* {index + 1}. {user.name}
* </li>
* )}
* </For>
* ```
*/
export function For<T>(props: ForProps<T>) {
return <>{props.each.map((item, i) => props.children(item, i))}</>;
}
14 changes: 14 additions & 0 deletions src/components/Match.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,20 @@ export type MatchProps = {
children: React.ReactNode;
};

/**
* Renders children only when `when` is truthy.
*
* @remarks
* `Match` is typically used inside `Switch`.
* For standalone conditional rendering, consider `Show`.
*
* @example
* ```tsx
* <Match when={isAdmin}>
* <p>Admin panel</p>
* </Match>
* ```
*/
export function Match(props: MatchProps) {
return <>{props.when ? props.children : null}</>;
}
10 changes: 10 additions & 0 deletions src/components/Show.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ export type ShowProps<T = unknown> = {
children: React.ReactNode;
};

/**
* Conditionally renders children when `when` is truthy, otherwise renders `fallback`.
*
* @example
* ```tsx
* <Show when={user} fallback={<p>Loading...</p>}>
* <p>Welcome back!</p>
* </Show>
* ```
*/
export function Show(props: ShowProps) {
return props.when ? <>{props.children}</> : <>{props.fallback}</>;
}
12 changes: 12 additions & 0 deletions src/components/Switch.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
import React from "react";
import { Match, MatchProps } from "./Match";

/**
* Renders the children of the first `Match` child whose `when` prop is truthy.
*
* @example
* ```tsx
* <Switch>
* <Match when={status === "loading"}>Loading...</Match>
* <Match when={status === "success"}>Done!</Match>
* <Match when={status === "error"}>Something went wrong.</Match>
* </Switch>
* ```
*/
export function Switch(props: { children: React.ReactNode }) {
const children = React.Children.toArray(props.children);

Expand Down
Loading