defineComponent
Registers a component under a name when its file loads, and returns the same component so it can also be imported and rendered directly.
import { defineComponent } from '@salla.sa/twilight-theme-engine';In plain words
Instead of writing a component and remembering to register it somewhere else, wrap it: export const Promo = defineComponent({ name: 'my-theme:promo', component: PromoImpl }).
The component is in the registry as soon as the file is imported, and Promo is still an ordinary component you can render.
Signature
function defineComponent<P = Record<string, unknown>>(config: {
name: string;
component: ComponentType<P>;
override?: boolean; // true: registry.override, otherwise registry.register
}): ComponentType<P>Try it live
// app/components/PromoStrip.tsx
import { defineComponent } from '@salla.sa/twilight-theme-engine';
export const PromoStrip = defineComponent({
name: 'my-theme:promo-strip',
component: function PromoStrip({ title, tone }: { title: string; tone: 'light' | 'dark' }) {
return <div className={`promo promo--${tone}`}>{title}</div>;
},
});
// Elsewhere, either way renders it:
// <PromoStrip title="Free delivery on orders over 200 SAR" tone="light" />
// <Component name="my-theme:promo-strip" title="Free delivery on orders over 200 SAR" tone="light" />
Example
import { defineComponent } from '@salla.sa/twilight-theme-engine';
export const PromoStrip = defineComponent({
name: 'my-theme:promo-strip',
component: function PromoStrip({ title }: { title: string }) {
return <div className="promo-strip">{title}</div>;
},
});
How it behaves
It returns
config.componentitself, not a wrapper, so props,displayNameand identity are unchanged.The config type (
DefineComponentConfig) is not exported; TypeScript infersPfromcomponent.
Gotchas
Registration is a side effect of importing the file. A file nothing imports never registers, and one imported only by a page registers only once that page loads. Import such files from
app/router.tsx.override: trueon a name nothing registered records no original, exactly likeregistry.override; forproduct:cardthat is not enough (see registry).
Related
The shared name-to-component table the engine consults for a few swappable parts: the product card, the product gallery and home blocks.
ComponentRenders the component registered under a name, passing every other prop to it, or a fallback when nothing is registered there.
registerComponents, overrideComponentsRegister or override many named components in one call, from an object whose keys are names and whose values are components.