0

I'm trying to understand react-dom/server.

I have a react application, using express as the server.

I have an express route like so :

var server = app.listen(3000);
app.get('/test', (req, res) => {                       
  const context = {}
  const html = ReactDOMServer.renderToString(
      <h1>foo</h1>
  )  
  if (context.url) {
    res.writeHead(302, {
      Location: context.url
    })
    res.end()
  } else {
    res.write(html)
    res.end()
  }
});

If I run the server file with node app-server, I get this error :

      <h1>adasd</h1>
      ^
SyntaxError: Unexpected token <

I passed JSX to renderToString based on the example there : https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/StaticRouter.md

How can I make the express server file processed this JSX code ?

For the client side, I use webpack with the babel loader, and it works fine.

trogne
  • 3,402
  • 3
  • 33
  • 50
  • also babel https://babeljs.io/docs/plugins/preset-react/ (you don't need webpack, babel is enough) – azium May 01 '18 at 18:30
  • Looking at the link. But how do you do that with my example ? I start my server using `node app-server.js` . I don't think it will read the ".babelrc" file, and there's no babel in the github link I provide. – trogne May 01 '18 at 18:42
  • 1
    use babel to compile, then run your compiled code. this is the only way it can work, its exactly what babel-loader is doing – azium May 01 '18 at 19:25
  • Thanks! It works after pasting the code in babeljs.io (with presets es2015 and react), and starting the node server with the resulted code. – trogne May 01 '18 at 19:38
  • sure, but use the babel cli instead of the website.. otherwise why bother use jsx at all – azium May 01 '18 at 19:44

1 Answers1

0

Thanks to @azium.

Solution was to first convert the ES6/JSX file with babel-cli .

I used this babel-cli command :

npx babel --no-babelrc script.js --out-file script-compiled.js --presets=es2015,react

npx is used to "execute npm package binaries"

trogne
  • 3,402
  • 3
  • 33
  • 50