Search code examples
reactjsreactjs-fluxisomorphic-javascript

reactJS : isomorphic app with flux


React-flux-cart . This example contains only client side code for react. How to make it isomorphic. What are the places where changes are required to include node and make it run as it is on server side also.


Solution

  • If you already use NodeJS, then it should not be too hard.

    I assume you already know how to call React.renderToString to render markup on the server. So what is left to be done is to render the markup that also display the data from the store.

    If you look at this store for example, the store data is defined at line #7

    var _products = {}, _cartVisible = false;
    

    What needs to be done is to set _products to some other data BEFORE you call React.renderToString. This is done via Actions in the Flux architecture (see how an action is invoked here at line #15).

    So, before you call React.renderToString, you have to call this to populate your store:

    var FluxCartActions = require('../actions/FluxCartActions');
    
    var sku = 123123;
    var update = {
      name: 'Scotch.io Signature Lager',
      price: 4.99,
      quantity: 1,
      type: '48oz bottle'
    };
    
    FluxCartActions.addToCart(sku, update);
    

    Where sku and update can be any data you want.

    For completeness, here is something you can do with ExpressJS

    // server.jsx
    var React = require('react');
    var FluxCartActions = require('./reactCode/actions/FluxCartActions');
    var FluxCartApp = require('./reactCode/components/FluxCartApp.react');
    var app = require('express')();
    
    app.get('*', function(req, res){
      var sku = 123123;
      var update = {
        name: 'Scotch.io Signature Lager',
        price: 4.99,
        quantity: 1,
        type: '48oz bottle'
      };
      FluxCartActions.addToCart(sku, update);
      var markup = React.renderToString(<FluxCartApp />);
      res.send(markup);
    });
    

    Note that this is a .jsx file, so use babel require hook to enable JSX in NodeJS.

    This is important. After you have your markup, you should clear your store before your next http request, otherwise, the previous data in your store will persist and visible for other requests.

    You should take a look at Alt because they make it easier to use Flux architecture than the implementation at Facebook. They also have functions such as bootstrap, and flush to help you populate your store, and reset your store without invoking an action or make any public accessor to your store. Alt is designed with server-side rendering in mind.