Ad

Transferring Props To Client Side While Doing Server Side Rendering Using Swig And Koa

- 1 answer

Here is my server.js

router.get('/react/:regioncode', function*(next) {
  var response =
    yield fnGetOffers(this.params.regioncode);
  var JsonResponse = JSON.parse(response);
  var offerHtml = ReactDOM.renderToString(ReactApp({
    offerAPI: JsonResponse
  }));
  this.body =
    yield render('index', {
      reactoffers: offerHtml,
      offerAPI : JsonResponse
    });
});

Server side rendering is happening fine but to attach the event handlers ,I need to load the data on the client side as well .I want to use the same JSON data on my client side and for that i do this :

var mountNode = document.getElementById('react-content');
ReactDOM.render( < ReactApp offerAPI = {
      offerAPI
    }
    />, mountnode);

Thing is I cannot get the offerAPI data in my client js and also my event handler doesn't get attached.

Ad

Answer

Normally when doing initial data handling into React (or any other JavaScript that relies on server side rendering) you'd put the content in a variable attached to the window object.

<html>
<body>
<script>
    window.offerAPI = {{{ offerAPI }}};
</script>
</body>
</html>

Which can be picked up by React like this:

var mountNode = document.getElementById('react-content');
ReactDOM.render( < ReactApp offerAPI = {
      window.offerAPI
    }
    />, mountnode);

This of course would be cleared after getting the data in order to not have it slushing around in the DOM uselessly.

Ad
source: stackoverflow.com
Ad