Server Side React Rendering
In order to understand server-side rendering in React, i created the most basic example using Express, Babel and Parcel.
Let's get started.
Our app's structure is going to be like this:
react-ssr-example/ ├─ src/ │ ├─ app.jsx ├─ client.js ├─ server.js ├─ package.json
At first, we are going to download the react
,
react-dom
, express
, parcel
and
nodemon
packages.
We also need to install @babel/preset-react
to support
.jsx
on Node and @babel/register
to compile
.jsx
on runtime since .jsx
files are not
natively supported by Node.
client.js
has react
imported and we hydrate
#root element where we render our app.
hydrateRoot
lets you display React components inside a
browser DOM node whose HTML content was previously generated by
react-dom/server
.
server.js
now has a Babel config file at the top. The rest
is a basic Express app.
createElement
creates React element from component.
renderToString
renders a React tree to an HTML string.
Finally, you can run npm run build
and then
npm start
and have a React SSR App up and running! 🚀