ui-render
Version:
Django-style render() for React : render(componentPath, props)
161 lines (104 loc) ⢠3.48 kB
Markdown
style render() for React & Vite
Render components by path or name with props ā no need for manual imports.
⨠Features
šÆ Render components dynamically with render(componentName, props)
ā” Zero-config with Vite (import.meta.glob)
š¦ Lightweight ā no runtime overhead
š Supports nested directories (shared/UserInfoCard)
ā
Works in both dev and production builds
š¦ Installation
npm install ui-render
This package requires React 18+ and Vite.
ā” Quick Start Example
Create a Vite + React project
``` bash
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
```
### Install ui-render
``` bash
npm install ui-render
```
-> Add lib/ui.ts
``` tsx
// src/lib/ui.ts
import { createRenderer } from "ui-render";
export const render = createRenderer({
baseDir: "src/components",
viteModules: import.meta.glob("/src/components/**/*.tsx"),
});
```
-> Create components
``` tsx
// src/components/Hero.tsx
export default function Hero({ title }: { title: string }) {
return <h1 className="text-3xl font-bold">{title}</h1>;
}
// src/components/About.tsx
export default function About() {
return <p className="text-gray-600">This is the about section.</p>;
}
// src/components/shared/UserInfoCard.tsx
export default function UserInfoCard({ name, email }: { name: string; email: string }) {
return (
<div className="border rounded p-4">
<h2 className="font-semibold">{name}</h2>
<p>{email}</p>
</div>
);
}
// Use in App.tsx
// src/App.tsx
import { render } from "@/lib/ui";
function App() {
return (
<div className="flex flex-col gap-4 p-6">
{render("Hero", { title: "Hello World!" })}
{render("About")}
{render("shared/UserInfoCard", {
name: "John Doe",
email: "john@example.com",
})}
</div>
);
}
export default App;
```
Run the app
``` bash
npm run dev
```
Open http://localhost:5173
š
| Option | Type | Required | Description |
| ------------ | ------------------------------------ | -------- | ---------------------------------- |
| `baseDir` | `string` | ā
| Root directory for components |
| `viteModules`| `Record<string, () => Promise<any>>` | ā
| Import map from `import.meta.glob` |
Returns a render function:
render(componentName: string, props?: Record<string, any>): ReactNode
| File Location | Render Key |
| ------------------------------------- | ----------------------- |
| `src/components/Hero.tsx` | `"Hero"` |
| `src/components/About.tsx` | `"About"` |
| `src/components/shared/UserInfoCard.tsx` | `"shared/UserInfoCard"` |
ā ļø **Important Warning**
Do **not** render a component inside itself using the `render()` function.
For example, avoid doing this inside `Home.tsx`:
```tsx
function Home() {
return (
<div>
{render("Home")} {/* ā This will cause infinite recursion */}
</div>
);
}
```
š Next Version goals
- Manifest support (non-Vite projects)
- Next.js RSC support
- Custom error fallback option
Django-