Skip to content

Commit

Permalink
Add createDynamic utility. (#2422)
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniGuardiola authored Feb 21, 2025
1 parent 0eab77d commit e897701
Showing 1 changed file with 26 additions and 7 deletions.
33 changes: 26 additions & 7 deletions packages/solid/web/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,30 +115,49 @@ export type DynamicProps<T extends ValidComponent, P = ComponentProps<T>> = {
};

/**
* Renders an arbitrary custom or native component and passes the other props
* Renders an arbitrary component or element with the given props
*
* This is a lower level version of the `Dynamic` component, useful for
* performance optimizations in libraries. Do not use this unless you know
* what you are doing.
* ```typescript
* <Dynamic component={multiline() ? 'textarea' : 'input'} value={value()} />
* const element = () => multiline() ? 'textarea' : 'input';
* createDynamic(element, { value: value() });
* ```
* @description https://docs.solidjs.com/reference/components/dynamic
*/
export function Dynamic<T extends ValidComponent>(props: DynamicProps<T>): JSX.Element {
const [p, others] = splitProps(props, ["component"]);
const cached = createMemo<Function | string>(() => p.component);
export function createDynamic<T extends ValidComponent>(
component: () => T,
props: ComponentProps<T>
): JSX.Element {
const cached = createMemo<Function | string>(component);
return createMemo(() => {
const component = cached();
switch (typeof component) {
case "function":
if (isDev) Object.assign(component, { [$DEVCOMP]: true });
return untrack(() => component(others));
return untrack(() => component(props));

case "string":
const isSvg = SVGElements.has(component);
const el = sharedConfig.context ? getNextElement() : createElement(component, isSvg);
spread(el, others, isSvg);
spread(el, props, isSvg);
return el;

default:
break;
}
}) as unknown as JSX.Element;
}

/**
* Renders an arbitrary custom or native component and passes the other props
* ```typescript
* <Dynamic component={multiline() ? 'textarea' : 'input'} value={value()} />
* ```
* @description https://docs.solidjs.com/reference/components/dynamic
*/
export function Dynamic<T extends ValidComponent>(props: DynamicProps<T>): JSX.Element {
const [p, others] = splitProps(props, ["component"]);
return createDynamic(() => p.component, others);
}

0 comments on commit e897701

Please sign in to comment.