Created
July 24, 2016 11:26
-
-
Save nadav-dav/b1f1d23c368354c2e3e4160bba46453c to your computer and use it in GitHub Desktop.
Server side render with React and Express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.get("*", (req, res, next)=>{ | |
ServerSideRenderer.render(req) | |
.then((results)=>{ | |
if (results.redirect) | |
res.redirect(302, results.redirect); | |
else if (results.html) { | |
res.status(200).render('index', {react: results.html}); | |
} else next(); | |
}, next); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var React = require('react'); | |
var ReactDom = require('react-dom/server'); | |
import {match, RouterContext} from "react-router"; | |
import Main from "../../app/Main"; | |
import routes from "../../app/routes"; | |
export default class ServerSideRenderer { | |
static render(req) { | |
return new Promise((resolve, reject)=> { | |
match({routes: routes(), location: req.url}, (error, redirectLocation, renderProps)=> { | |
if (error) { | |
reject(error); | |
} else if (redirectLocation) { | |
resolve(REDIRECT(redirectLocation.pathname + redirectLocation.search)) | |
} else if (renderProps) { | |
resolve(HTML( | |
ReactDom.renderToString( | |
<Main children={renderProps.children}> | |
<RouterContext {...renderProps}/> | |
</Main> | |
) | |
)); | |
} else { | |
reject(); | |
} | |
}); | |
}) | |
} | |
} | |
const REDIRECT = (redirect) => ({redirect}); | |
const HTML = (html) => ({html}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment