Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using express and es6 to render react and jsx server side

I am trying to wire up a minimum proof-of-concept to render a single React component server-side.

When I run my app, I get an error:

SyntaxError: express.js: Unexpected token (10:41)

And the offending line is:

> 10 |   res.send(ReactDOMServer.renderToString(<Component msg={msg} />));
     |                                          ^

This is my package.json:

{
  "name": "ssrReact",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "nodemon express.js --exec babel-node --presets es2015,stage-2"
  },
  "dependencies": {
    "express": "^4.14.1",
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  },
  "devDependencies": {
    "babel-cli": "^6.22.2",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-stage-2": "^6.22.0",
    "nodemon": "^1.11.0"
  }
}

This is my Component.js:

import React from 'react';

class Component extends React.Component {
  render() {
    return <h1>Hello, {this.props.msg}</h1>;
  }
}

export default Component;

This is my express.js:

import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Component from './Component';

const app = express();

function home (req, res) {
  const msg = req.params.msg || 'Hello';
  res.send(ReactDOMServer.renderToString(<Component msg={msg} />));
}

app.get('/', home);
app.get('/:msg', home);

app.listen(3333);

What do I need to change in order to allow Express to serve a React component?

Thanks for the help.

like image 779
SeanPlusPlus Avatar asked Feb 11 '17 21:02

SeanPlusPlus


People also ask

Does express do server-side rendering?

On the server side, we use express to define a root endpoint which serves a index. html file. When a request is received, we render our React app root component App to a string using ReactDOMServer. renderToString .

Can React be rendered on server-side?

Yes! This is where server-side rendering for React comes in. In this article, I want to introduce you to server-side rending (SSR) with React, reasons to use it, and some popular frameworks for rendering React on the server side.

Is React rendering server-side or client-side?

Client-Side Rendering By default, your React app will be client-side rendered. This means basically, all of the source code will live in JavaScript files referenced in a single HTML file that initializes your app.


1 Answers

My two cents, do:

npm i -D babel-preset-react

And change your running script to:

"scripts": {
    "start": "nodemon express.js --exec babel-node --presets es2015,stage-2,react"
  },

To parse jsx you need to install the babel-preset-react

like image 101
Fabio Antunes Avatar answered Sep 21 '22 21:09

Fabio Antunes