React/Express - 'Unexpected token <' in call to renderToString()
I believe the issue stems from the fact that requiring babel-register
will not work for the file you import it in, but for files that get imported afterwards. So the JSX syntax of <RouterContext
will not be picked up by the renderToString
method. This has happened to me before and including babel-register
for the syntax never felt clean to me anyway.
What I personally have done and many others do is this: readDomServer.renderToString(React.createElement(RoutingContext, props))
using the createElement
method in React, you can accomplish the same thing. This will solve your issue.
babel-register
doesn't process the file it is called from, see https://stackoverflow.com/a/29425761/1795821
You'll need to put the app.get()
called into another file, or use a different method of loading Babel.
So make a new renderReact.js
file with
module.exports = function(app) {
app.get('*', (req, res) => {
match({ routes: routes, location: req.url }, (err, redirect, props) => {
const appHtml = reactDomServer.renderToString(<RouterContext {...props}/>)
res.send(renderPage(appHtml))
})
})
}
Then back in your index.js
do this instead
let renderReact = require('./renderReact.js');
renderReact(app);