react-chousy API & Usage
Full API and usage documentation for react-chousy.
Overview
react-chousy
provides three main components for clean, declarative conditional and list rendering in React:
ConditionalRender
SwitchCaseRender
ChousyEach
Installation
npm install react-chousy
ConditionalRender
Render content based on a boolean condition.
<ConditionalRender condition={isLoggedIn}>
{{
true: <p>Welcome, hero 🦸!</p>,
false: <p>Access denied! 🚫 Please log in.</p>
}}
</ConditionalRender>
ConditionalRender API
Prop | Type | Description |
---|---|---|
condition | boolean | The condition to evaluate |
children | object | { true, false } JSX content |
SwitchCaseRender
A JSX-friendly alternative to switch statements.
<SwitchCaseRender value={status}>
{{
idle: <p>Waiting...</p>,
loading: <p>Loading...</p>,
success: <p>✅ Success!</p>,
error: <p>❌ Error</p>,
default: <p>Unknown status</p>
}}
</SwitchCaseRender>
SwitchCaseRender API
Prop | Type | Description |
---|---|---|
value | string | number | The value to match |
children | object | Keys that match the value + optional default |
ChousyEach
A declarative, flexible way to render lists, inspired by Ruby/Rails' each
.
const fruits = ['🍎', '🍌', '🍇'];
<ChousyEach of={fruits}>
{(fruit, idx) => (
<span>{fruit}</span>
)}
</ChousyEach>
With selection state
<ChousyEach of={fruits} trackSelection>
{(fruit, idx, { selectedIdx, setSelectedIdx }) => (
<button
className={selectedIdx === idx ? 'font-bold text-blue-600' : 'text-gray-700'}
onClick={() => setSelectedIdx(idx)}
>
{fruit}
</button>
)}
</ChousyEach>
Navbar highlighting
const menu = [
{ label: 'Home', path: '/' },
{ label: 'About', path: '/about' },
{ label: 'Contact', path: '/contact' },
];
const currentPath = '/about';
<ChousyEach
of={menu}
navHighlight
getPath={item => item.path}
currentPath={currentPath}
>
{(item, idx, { isActive }) => (
<a
href={item.path}
className={isActive ? 'text-blue-600 font-bold' : 'text-gray-700'}
>
{item.label}
</a>
)}
</ChousyEach>
ChousyEach API
Prop | Type | Description |
---|---|---|
of | array | Array of items to render |
children | function | Render function for each item. Helpers for selection/highlight |
className | string | Optional Tailwind classes for the <ul> |
onChange | function | Optional effect callback when list changes |
trackSelection | boolean | If true, exposes selectedIdx and setSelectedIdx to children |
navHighlight | boolean | If true, highlights the item whose path matches currentPath |
getPath | function | Function to extract the path from each item |
currentPath | string | The current path to match for highlighting |
For more, see the react-chousy npm page or GitHub repo.