Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Middleware function creates a `ctx.render('homepage', { title, foo })`
- // function on the koa context.
- const reactRenderware = (root, _opts = {}) => {
- const defaultOpts = () => ({ locals: {} })
- const { locals: globals, opts } = { ...defaultOpts(), ..._opts }
- const { extname } = require('path')
- const React = require('react')
- const ReactDOMServer = require('react-dom/server')
- const Master = require(path.join(root, 'master.jsx'))
- return async (ctx, next) => {
- ctx.render = (templatePath, locals) => {
- const fullpath = path.join(
- root,
- extname(templatePath) ? templatePath : templatePath + '.jsx'
- )
- const Template = require(fullpath)
- ctx.type = 'html'
- const output = new (require('stream')).PassThrough()
- output.write('<!doctype html>')
- ReactDOMServer.renderToStaticNodeStream(
- <Master {...globals} {...locals} ctx={ctx}>
- <Template {...locals} ctx={ctx} />
- </Master>
- ).pipe(output)
- ctx.body = output
- }
- return next()
- }
- }
- // views
- // - master.jsx
- // - homepage.jsx
- // src
- // - index.js <-- We are here
- const viewRoot = require('path').join(__dirname, '../views')
- // Apply middleware
- app.use(reactRenderware(viewRoot))
- // Example route
- app.use(async ctx => {
- const messages = await db.latestMessages()
- await ctx.render('homepage', {
- messages
- })
- })
Add Comment
Please, Sign In to add comment