Search code examples
renderingreactjsecmascript-6koaisomorphic-javascript

Isomorphically render html string with Koa


I'm trying to get Koa to isomorphically render a html string it receives from react-router.

Here's the code I've been trying to make work:

server.js

import koa from 'koa';
import React from "react";
import Router from "react-router";
import routes from "./routes";
const server = koa();
const port = process.env.NODE_ENV || 8000;

server.use(function *() {
    try {
        yield Router.run(routes, this.request.url, function (Handler) {
            var content = React.renderToString(<Handler/>)
            this.body = content
        })
    }
    catch (err) {
        this.status = err.status || 500;
        this.body = err.message;
        this.app.emit('error', err, this);
    }
 })

server.listen(port, function(err) {
  if (err) throw err;
  console.log("Server running on: http://localhost:"+port)
})

routes.js

import React from "react"
import {Route, DefaultRoute} from "react-router"
import Main from "./components/main"


export default (
  <Route path="/">
    <DefaultRoute handler={Main} name="main" />
  </Route>
)

main.js

import React from "react"

const Main = React.createFactory(React.createClass ({
  render () {
    return (
      <div>HELLO</div>
    )
  }
}))

export default Main

Getting several errors:

Warning: Component(...): No render method found on the returned component instance: you may have forgotten to define render in your component or you may have accidentally tried to render an element whose type is a function that isn't a React component.

Warning: Don't set the props property of the React element. Instead, specify the correct value when initially creating the element.

TypeError: Can't add property context, object is not extensible

Warning: Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory


Solution

  • for those who needs an answer with this, hope this will help you guys.

    server.js

    import koa from 'koa';
    import React from "react";
    import Router from "react-router";
    import routes from "./routes";
    const server = koa();
    
    let handler;
    
    server.use(function *(next) {
      Router.run(routes, this.request.url, (Handler) => {
        handler = React.renderToString(<Handler/>);
      });
      yield next;
    });
    
    server.use(function *() {
      this.body = handler;
    });
    
    export default server;
    

    components/index.js

    import React from "react";
    
    const Main = React.createClass ({
      render () {
        return (
          <div>HELLO</div>
        );
      }
    });
    
    export default Main;
    

    i dont see the need to create factory for this one.