Bruno Portis
Bruno Portis

Reputation: 160

Babel 6 + React - Passing initial data (In-browser transpiler)

I`m using React + Babel 6, with webpack. When I was using Babel 5, it was easy to pass in the initial data using a script type="text/babel" on the page, then babel-core/browser.js takes care of it.

But now, using Babel 6, I have to load all the initial data calling the REST API, as my component mounts.

This results in the browser client opening a connection on the server to render the frontend, and then the frontend opens a new connection to get the data.

Wouldn't this affect my server performance as, now I have 2 connections vs the older 1 connection oppened?

EDIT:

I wish I could keep using the folowing snippet on the page:

<script type="text/javascript" src="{{ asset('app/bundle.js') }}"></script>
<script type="text/babel"> 
    var jsonVar = '{vars}';

    ReactDOM.render(
        <App vars={vars}/>,
        document.getElementById('app-wrapper')
    );
</script>

Upvotes: 1

Views: 207

Answers (2)

Bruno Portis
Bruno Portis

Reputation: 160

I've resolved this issue by: Using an "application/json" script tag(passing an id) and put serialized data inside it.

<script type="application/json" id="app-data"> { "id" : 1 } </script>

Then in the app.js:

var appData =  JSON.parse( document.getElementById(script-id).innerHTML )

Upvotes: 0

luiscrjr
luiscrjr

Reputation: 7268

It's a normal pattern to load your server side content and, then, your components grab some data. One downside of this design, of course, is that this implies one initial render plus api request for data.

However, you can setup a server side render with react components, rendering initial data on the server. If your backend is nodejs, for instance, you can use ReactDOMServer.renderToString.

Upvotes: 1

Related Questions