Rendering React components to a HTML string in Deno

You can find the full source at https://github.com/francium/deno-react-renderTostring-demo

Example Output

<div class="class-name-foo"><p>Count is <!-- -->0</p><p>IP is <!-- -->unknown</p><p>Random number is <!-- -->0.9431874610921576</p><p><div style="outline:1px dashed;padding:5px;margin:5px"><p>This is a child component</p><p>Label is <!-- -->a</p></div><div style="outline:1px dashed;padding:5px;margin:5px"><p>This is a child component</p><p>Label is <!-- -->b</p></div></p></div>

And with pretty printing,

<div class="class-name-foo">
  <p>Count is
    <!-- -->0
  </p>
  <p>IP is
    <!-- -->unknown
  </p>
  <p>Random number is
    <!-- -->0.9431874610921576
  </p>
  <p>
    <div style="outline:1px dashed;padding:5px;margin:5px">
      <p>This is a child component</p>
      <p>Label is
        <!-- -->a
      </p>
    </div>
    <div style="outline:1px dashed;padding:5px;margin:5px">
      <p>This is a child component</p>
      <p>Label is
        <!-- -->b
      </p>
    </div>
  </p>
</div>

How it works

There’s a bit of implicit magic happening to make it work and not to see errors in your editor when opening the sources.

First the deno.json config needs the following,

{
  "importMap": "import_map.json",
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "react"
  }
}

And secondly the import_map.json needs,

{
  "imports": {
    "react/jsx-runtime": "https://esm.sh/react@18.2.0/jsx-runtime"
  }
}

To render the components to a HTML string, in main.ts, we can do,

import React from "npm:react";
import { renderToString } from "npm:react-dom/server";
import App from "./App.tsx";

const html = renderToString(React.createElement(App));
console.log(html);

Alternatively, we could also rename main.ts to main.tsx, which allows usage of JSX syntax,

  import React from "npm:react";
  import { renderToString } from "npm:react-dom/server";
  import App from "./App.tsx";

- const html = renderToString(React.createElement(App));
+ const html = renderToString(<App />);
  console.log(html);

Contents