Bolboa Bolboa - 3 months ago 18
Jade Question

React server side rendering wrong page

In my

app.js
I have two parts...

app.use('/', index);
app.use('/register', reg);


An index part and a register part.

In my
index.js
I am rendering the following...

var React = require('react');
var reactDom = require('react-dom/server');
var RegApp = React.createFactory(require('../components/index'));

router.get('/', function(req,res) {
var reactHtml = reactDom.renderToString(RegApp({exists: false}));
res.render('../../tutorHub/views/index.jade', {reactOutput: reactHtml});
});


This is calling the following react component to be rendered...

class RegApp extends React.Component {
constructor(props) {
super(props);
}
render(){

return (
<Register />
);
}
}
module.exports = RegApp;


So the first page a user will see is the
<Register />
component. Now, in my other route, the
register.js
I am querying the db and rendering the page based on the result.

In short I am attempting to render another component to replace the one I rendered above...

var React = require('react');
var reactDom = require('react-dom/server');
var App = React.createFactory(require('../components/index'));

router.post('/', function (req, res) {
//Here I query the db

...
console.log("query success");
var reactHtml = reactDom.renderToString(App({exists: true}));
res.render('../../tutorHub/views/index.jade', {reactOutput: reactHtml});


The component that this is trying to render is the following...

class App extends React.Component {
constructor(props) {
super(props);
}
render(){

return (
<Index />
);
}
}
module.exports = App;


The problem is, this component never gets rendered. The page refreshes and renders the first component
<Register />
instead of
<Index />
. This is all very confusing because the console prints
query success
, but still the page is not rendered. Even if I put a
console.log
inside of the
App
component's render method, it gets printed out but the page is not rendered. How can I fix this?

Answer

You seem to be passing in the Register component for the path: /

router.get('/', function(req,res) {
    var reactHtml = reactDom.renderToString(RegApp({exists: false}));
    res.render('../../tutorHub/views/index.jade', {reactOutput: reactHtml});
});

Either the path should be /register in the above or the component should be the App component.