4

I have an app and part of it is to login with twitter. After successfully logged in, I will usually pass the user data to the template by

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 render the template based on the user data.

But in React, how should I pass such data to the component after logged in?

I am thinking of putting the data in the browser directly, but I am not confident about that.

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

How do you think?? Thanks.

2 Answers 2

5

Usually you send the props you pass to the top level component to the client in a script tag.

So, you're doing <MyApp user={user} /> or MyApp({user: user}), you would create a script tag like this:

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

And on the client side:

React.renderComponent(MyApp(__react_preload_data), document.body);
Sign up to request clarification or add additional context in comments.

1 Comment

@user3470929 please create a new question instead of asking one in a comment.
0

There is a library that works well with express (and any other view rendering node framework) called react-helper (https://github.com/tswayne/react-helper). It pretty much handles everything you need to do to render react components in your view and pass data to them from the server in any node framework. You just make an entry point (js file) for webpack (the lib has a cli that can generate your webpack config for you) and add a line to your controller and view and your component will render on that page. Passing data into your react components is really simple:

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

There is also express middleware for react-helper (https://github.com/tswayne/express-react-helper) that allows you to add context that is available to all views, which is convenient for user session data.

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

Then, all of your react components will have the user prop without having to manually add that logic to every controller action.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.