Rendering components in Node.js means rendering to strings, instead of trying to figure out the best way to insert them into the DOM. The string content is then returned to the browser, which displays this to the user immediately. Let's look at an example:
- Here is the component to render:
import React from "react";
import PropTypes from "prop-types";
export default function App({ items }) {
return (
<ul>
{items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}
App.propTypes = {
items: PropTypes.arrayOf(PropTypes.string).isRequired
};
- Next, let's implement the server that will render this component when the browser asks for it:
import React from "react";
import { renderToString } from "react-dom/server";
import express from "express";
import App from "./App";
const doc = content =>
`
<!doctype html>
<html>
<head>
...