BLOG.siposdani87

Use render and unmount on React and SolidJS

Define these functions to mount components
By: Dániel Sipos on

The both library, React and SolidJS are the most powerful component renders at this time. I like to work both of them! Sometimes it is necessary to use native render and unmount methods in typescript, if you don’t use these as a framework, only as a library.

So I show you, how you use these component renderers in the 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();
};

Last words

These utility methods help ours to make my coding life easier! Let’s use it!

Share with your friends

Related posts