fingercross
fingercross

Reputation: 661

React Server Side Rendering with react-router

My simple web app have two pages. (Express as server)

/home

/item

  1. To test if the page is render in both server and client. I print a text to the console. I can see the text 'render' in console of server and client, if i directly type the url localhost:3000/item in browser. However, if I access the item page via the <Link to="item">Item</Link> in home page. I can see the 'render' in client side only but not in server side? So I think it is not render in server side. Or am I misunderstanding something? can anyone tell me?

  2. another question is: I would like to use the same code to generate a phonegap app running in android. Is there a problem if I use React server side rendering? Or should I use React client side rendering and then call a restful to get data?

  3. one more question: when I use this code in server it give me a "unexpected token <" error

React.renderToString(< Handler />)

So that I changed to

React.renderToString(React.createElement(Handler))

How to setup the server so that it know how to parse jsx code?

Thanks everyone

item.js

var React = require('react'),
DOM = React.DOM, div = DOM.div, button = DOM.button, ul = DOM.ul, li = DOM.li    

// This is just a simple example of a component that can be rendered on both
// the server and browser

module.exports = React.createClass({
    getInitialState: function() {
        console.log('getInitialState');      
        return {
            count: 0//this.props.initialCount
        };
    },

    _increment: function() {
      console.log('_increment');
      this.setState({ count: this.state.count + 1 });
    },

    render: function() {
        console.log('render');
        return div({onClick:this._increment}, this.state.count);                  
    }
});

server.js

app.use(function (req, res) {
  Router.run(routes, req.path, function (Handler) {    
    res.send('<!DOCTYPE html>' + React.renderToString(React.createElement(Handler)));
  });
});

browser.js

var React = require('react');
var Router = require('react-router');
var routes = require('./routes');

//var Info = require ('./pages/info.jsx');


 /*React.render(
        <h1>Hello, world!</h1>,
        document.getElementById('main')
      );*/

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler />, document);
});

Upvotes: 1

Views: 638

Answers (1)

Ben S
Ben S

Reputation: 41

To answer question 1. If you are clicking a link on the web page it means the web server has already dumped the generated HTML onto the client. This means hat react on the client will take over, so you will see no output on the server. However if you visit the URL you are hitting the server, hence seeing the console log on the server. Hope that makes sense.

Upvotes: 0

Related Questions