Skip to main content
BLOG.siposdani87

Use render and unmount on React and SolidJS

Utility functions for programmatic component mounting in React and SolidJS

By Dániel Sipos
· · 1 min read

Both React and SolidJS are popular component rendering libraries. Sometimes it is necessary to use their native render and unmount methods directly in TypeScript, especially when using them as libraries rather than full frameworks.

This article demonstrates how to use these component renderers in a browser environment.

React

import { ComponentClass, createElement, FunctionComponent } from 'react';
import * as ReactDOM from 'react-dom/client';

export const renderReact = (
	type: FunctionComponent | ComponentClass | string,
	props: Object,
	mountNode: HTMLElement
): ReactDOM.Root => {
	const root = ReactDOM.createRoot(mountNode);
	root.render(createElement(type, props));

	return root;
};

export const unmountReact = (reactRoot: ReactDOM.Root): void => {
	reactRoot.unmount();
};

SolidJS

import { render } from 'solid-js/web';
import { Component } from 'solid-js';

export type Dispose = () => void;

export const renderSolid = <P>(
	component: Component<P>,
	props: P,
	mountNode: HTMLElement
): Dispose => {
	return render(() => component.call(this, props), mountNode);
};

export const unmountSolid = (dispose: Dispose): void => {
	dispose();
};

Conclusion

These utility methods provide a clean abstraction for mounting and unmounting components programmatically, which is useful when integrating React or SolidJS into non-SPA contexts.

Share with your friends

Related posts