DEV Community

Cover image for Render bare-bones React app as HTML in Tino
Marko Jakic
Marko Jakic

Posted on

Render bare-bones React app as HTML in Tino

Recently I've published Tino functional HTTP server for Deno, and you can read a short overview about it here.

This time I would like to show how you can easily render HTML content using middlewares.

Middlewares in Tino are composition of functions which whatever they return is passed through until your controller receives it.

Using Deno's TextDecoder and readFile top level APIs and Tino's withMiddlewares helper for composing middlewares you can write a simple endpoint definition in the following manner: (for example app.js file)

// app.js
const htmlReader = async () => {
  const decoder = new TextDecoder("utf-8");
  const html = await Deno.readFile("./react.html");
  return { html: decoder.decode(html) };
}

const composedReact = withMiddlewares(htmlReader);
const useHTML = composedReact(({ html }) => ({ resp: html, type: "text/html" }));

app.get(() => ({ path: "/react", use: useHTML }));
Enter fullscreen mode Exit fullscreen mode

Now you need to create your React app as a website somewhere. I won't be using JSX here for simplicity but only React's createElement. Let's say you have your boilerplate saved in ./react.html file (same directory as your app.js file). Have a look at sample content below. All it does is handling "Inc" button and logging incremented value to the console:

<html>

<head>
  <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
</head>

<body>
  <div id="root"></div>
  <script>
    const e = React.createElement;
    const domContainer = document.querySelector('#root');
    const IncButton = () => {
      const [incrementedValue, inc] = React.useState(0);
      return e(
        'button',
        {
          onClick: () => {
            inc(incrementedValue + 1);
            console.log(incrementedValue);
          }
        },
        'Inc'
      );
    };
    ReactDOM.render(e(IncButton), domContainer);
  </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Now when you target http://localhost:8000/react you should see your React app running in the browser.

Hope you liked this post and how using middlewares you can process pretty much anything in Tino and write your own.

Cheers! 🍻

Top comments (0)