feat: add utility for readable looping and conditional rendering of components
This commit is contained in:
@@ -6,3 +6,4 @@ export * from './local-storage';
|
||||
export * from './cookies';
|
||||
export * from './session';
|
||||
export * from './constants';
|
||||
export * from './logic';
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
export interface ForProps<T, U> {
|
||||
data: readonly T[]
|
||||
children: (item: T, index: number) => U | null
|
||||
fallback?: React.ReactNode | null
|
||||
}
|
||||
|
||||
/**
|
||||
* A functional component that renders a list of children components from a given
|
||||
* array of data.
|
||||
*
|
||||
* @param data - The array of data to render
|
||||
* @param children - A function that takes the current item and index and returns
|
||||
* the child component to render
|
||||
* @param fallback - An optional fallback component to render when the data is empty
|
||||
*
|
||||
* @returns An array of rendered child components if the data is not empty, otherwise
|
||||
* the fallback component if it is provided, null otherwise
|
||||
*/
|
||||
export function For<T, U extends React.JSX.Element>({
|
||||
data,
|
||||
children,
|
||||
fallback = null
|
||||
}: ForProps<T, U>): (U | null)[] | React.ReactNode | null {
|
||||
if (!Array.isArray(data) || !data?.length) return fallback
|
||||
|
||||
return data.map((item, idx) => children(item, idx))
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './for'
|
||||
export * from './show'
|
||||
@@ -0,0 +1,19 @@
|
||||
export interface ShowProps {
|
||||
condition: boolean
|
||||
children: React.ReactNode
|
||||
fallback?: React.ReactNode | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Conditionally renders the `children` component if `condition` is true. If
|
||||
* `condition` is false, renders the `fallback` component instead.
|
||||
*
|
||||
* If `fallback` is `null`, renders nothing.
|
||||
*
|
||||
* @param condition - The condition to check
|
||||
* @param children - The component to render if `condition` is true
|
||||
* @param fallback - The component to render if `condition` is false
|
||||
*/
|
||||
export function Show({ condition, children, fallback = null }: ShowProps) {
|
||||
return condition ? children : fallback
|
||||
}
|
||||
Reference in New Issue
Block a user