React server side rendering in express (typescript guide)
Using JSX and TSX in Express.js - Learn how to render static HTML pages for each page request by integrating React components and TypeScript.
In Express JS you can use template engines to render views. You can also replace your views with React JSX components and render them to static HTML for each page request.
Install react-dom
In an existing Express project install react-dom
and react
:
npm install --save react-dom react
Next setup tsconfig.json
Configure typescript to process jsx in your tsconfig.json
file:
{
"jsx": "react"
}
Create a view
Create a .tsx
file and export a JSX element:
import React from "react";
export function Home() {
return <div>
<h1 className={'h1'}>Hi</h1>
</div>
}
Render the view on page request
Inside a express route callback handler render the view to a buffer and send:
export function renderReact(res: Response, x: JSX.Element) {
// render the element
const root = ReactDOMServer.renderToStaticMarkup(x);
// embed in HTML template
const html = `<html lang="en">
<body>
<main id="root">${root}</main>
</body>
</html>`
// send response
res.status(200).contentType('text/html').send(Buffer.from(html))
}
Now call this with a JSX component in your route:
app.get("/", function (req, res) {
renderReact(res, Home())
});