Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add createDynamic utility. #2422

Merged
merged 1 commit into from
Feb 21, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
Loading