Data transfer for viewing in ExpressJS + Reactjs

I have an application, and part of it is to log in to Twitter. After a successful login, I usually pass the user data to the template

app.get('/', function(req, res, next) {
        log("The Home page has the user info: ", req.session.user);
        res.render('pages/home', {
            app: 'home',
            user: req.session.user || '' 
        });
    });

And then you can display the template based on the data user.

But in React, how do you pass such data to a component after logging in?

I am thinking of direct data placement in the browser, but I am not sure about that.

<script type="javascript">
  var user = #{user}
</script>

What do you think??? Thank.

+4
source share
2 answers

Usually you send the details that you pass to the top-level client in a script tag.

So you do <MyApp user={user} />or MyApp({user: user}), you should create a script tag as follows:

var code = "<script>var __react_preload_data = " 
           + JSON.stringify({user: user}) 
           + ";</script>";

:

React.renderComponent(MyApp(__react_preload_data), document.body);
+5

, express ( node framework), response-helper (https://github.com/tswayne/react-helper). , , node. (js ) webpack ( lib cli, webpack ), , . :

const component = reactHelper.renderComponent('MyComponent', {user: 
req.session.user || ''})
res.render('view-to-render', {component})

- (https://github.com/tswayne/express-react-helper), , , .

app.use(function(req, res, next) {
 req.reactHelperContext.user = req.session.user || '';
});

.

0

All Articles