1

I'm rendering a page on get and passing a json object with it, like so:

/* GET home page. */
router.get('/', (req, res, next) => {
  const message = req.session.message;
  res.render('index', { data: message });
});

This is my index.ejs view:

<!DOCTYPE html>
<html>
  <head>
    <title>My Title</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <div id='react-app'> Loading &hellip;</div>
  </body>
  <script src="/javascripts/build.js"></script>
</html>

The page that's being rendered is index.js:

import React from 'react';

import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import { render } from 'react-dom';

import 'bootstrap/dist/css/bootstrap.min.css';
import './css/msha.scss';

import Store from './store';
import TemplateContainer from './components/TemplateContainer';

const renderApp = (Component) => {
  render(
    <AppContainer>
      <Provider store={Store}>
        <Component />
      </Provider>
    </AppContainer>,
    document.querySelector('#react-app'),
  );
};

renderApp(TemplateContainer);

if (module && module.hot) {
  module.hot.accept('./components/TemplateContainer', () => {
    renderApp(TemplateContainer);
  });
}

The page being rendered contains a react component. How do I access this data inside the react component?

3
  • 1
    What template engine do you use? And show your index view code. Commented Aug 8, 2017 at 21:46
  • I just added my index.ejs. Commented Aug 8, 2017 at 21:50
  • 1
    I would say the easiest way would be to make an express route that returns the data as json, instead of trying to pass it through your rendering engine. then in your react app make an ajax call for it when it loads Commented Aug 8, 2017 at 21:50

1 Answer 1

2

one of the ways is to add an object to the global scope and use it from the component:

<!DOCTYPE html>
<html>
  <head>
    <title>My Title</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <div id='react-app'> Loading &hellip;</div>
    <script>
      window.data = <%- JSON.stringify(data) %>;
    </script>
    <script src="/javascripts/build.js"></script>
  </body>
</html>
Sign up to request clarification or add additional context in comments.

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.