Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add React to an Express app?

I'm developing an app using Express and I'd like to run React on the front-end. How should I go about this?

I've seen people adding script tags (using CNDs) to their layout files, others using many npm packages...

What is the easiest way?

like image 292
Fábio Queluci Avatar asked Nov 20 '25 19:11

Fábio Queluci


1 Answers

ES6 (with Babel) is used, buy you don't have to.

server.js

import "babel-core/polyfill";
import path from "path";
import express from "express";
import React, { DOM } from "react";
import ServerDOM from "react-dom/server";
import Html from "./components/Html";

const server = express();

server.set("port", (process.env.PORT || config.port));
server.use(express.static(path.join(__dirname, "public")));
server.use("/", (req, res, next) =>
{
    const html = ServerDOM.renderToStaticMarkup(React.createElement(Html));
    res.status(200).send("<!doctype html>" + html);
});

server.get("*", async (req, res, next) =>
{
    try
    {
        let statusCode = 200;
        const html = ServerDOM.renderToStaticMarkup(React.createElement(Html));

        res.status(statusCode).send("<!doctype html>" + html);
    }
    catch (e) { next(e) }
});

server.listen(server.get("port"), () =>
{
    console.log("\nServer running at localhost:%d\n", server.get("port"));
});

Html.js (component)

import React, { Component, PropTypes, DOM, createElement as $ } from "react";

class Html extends Component
{
    static propTypes =
    {
        title: PropTypes.string,
        description: PropTypes.string
    };

    static defaultProps =
    {
        title: "",
        description: ""
    };

    render()
    {
        const { title, description, children } = this.props;

        return (
            DOM.html({},
                DOM.head({},
                    DOM.meta({charSet: "utf-8"}),
                    DOM.meta({httpEquiv: "X-UA-Compatible", content: "IE=edge"}),
                    DOM.meta({name: "description", content: description}),
                    DOM.meta({name: "viewport", content: "width=device-width, initial-scale=1"}),
                    DOM.link({rel: "stylesheet", href: "/app.css", type: "text/css"}),
                    DOM.title({}, title)
                ),
                DOM.body({},
                    DOM.div({id: "app"}, children),
                    DOM.script({src: "/app.js"})
                )
            )
        )
    }
}

export default Html;

In theory, you are setting up simple express server and using ServerDOM which is react js server side rendering to render the Html component. Then you including file like app.js which could be a bundle compiled using something like webpack (only if you want, I'll extremely recommend it) then you simply put it on the Html component and you done.

like image 163
Ido Avatar answered Nov 22 '25 12:11

Ido