Sharing & Overriding Components
Learn how to create reusable components and customize them without modifying the original code using the JopiJS alias system.
One of JopiJS's greatest strengths is its ability to make your React components modular.
Instead of importing a file via a complex path (../../components/Button), you use a virtual name (alias). This allows any module to provide, or replace, that component.
In this tutorial, we will first learn how to create and share a simple button.
Prerequisites:
- Project initialized with
minimaltemplate (see here for instructions). - Server running (
npm run start:dev_server).
Creating a Shared Component (The Basics)
Let's imagine you have a module for your UI components.
Create a folder src/mod_uikit/@alias/ui/SuperButton/.
In this folder, create the component file index.tsx:
// src/mod_uikit/@alias/ui/SuperButton/index.tsx
export default function SuperButton({ label }: { label: string }) {
return (
<button className="px-4 py-2 bg-blue-500 text-white rounded">
{label} (Original Version)
</button>
);
}This SuperButton folder in @alias/ui automatically acts as a declaration of the "SuperButton" component to the JopiJS system.
Using the Component
Now, let's use this button in our main application.
Go to one of your pages (e.g., src/mod_uikit/@routes/page.tsx).
The import is done via the magic alias @/ui/:
// src/mod_uikit/@routes/page.tsx
import SuperButton from "@/ui/SuperButton";
export default function HomePage() {
return (
<div className="p-10">
<h1>Welcome</h1>
<SuperButton label="Click Me" />
</div>
);
}If you start your server and got to http://localhost:3000, you will see the blue button appear.
Overriding our Component
Now, imagine another developer wants to change this button to Red without modifying your mod_uikit.
They can create a new module mod_myOverride and override SuperButton.
- Create
src/mod_myOverride/@alias/ui/SuperButton/. - Add a file named
high.priorityinside. - Create
index.tsxwith this content:
// src/mod_myOverride/@alias/ui/SuperButton/index.tsx
export default function SuperButtonRed({ label }: { label: string }) {
return (
<button className="px-4 py-2 bg-red-600 text-white rounded">
{label} (Red Version!)
</button>
);
}Now, refresh the page. The button is Red, even though mod_uikit still defines it as Blue!