Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access DOM with server-side render - react 0.14.1, react-dom 0.14.1 and react-router 1.0.0-rc3

I can't access the DOM with server implementation of react, react-dom and react-router. I either have ReferenceError: document is not defined, or Browser history needs a DOM errors.

Server entry:

module.exports = function( req, res, next ) {
  match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
    if (error) {
        res
            .status(500)
            .send(error.message);
    } else if (redirectLocation) {
        res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if (renderProps) {
        res
            .status( 200 )
            .set( 'Content-Type', 'text/html' )
            .send( '<!doctype html>' +
                renderToString(
                    [ <RoutingContext {...renderProps} />,
                    <HtmlDocument /> ]
                )
            );
    } else {
        res
            .status(404)
            .send('Not found');
    }
  })
};

client.js:

import { render } from 'react-dom';
import routes from './routes';

render( routes, document.getElementById('app') )

routes.jsx:

import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';

import Application from './Application';
import Index from './pages/index';
import App from './pages/app';
import Auth from './pages/auth';
import Login from './pages/auth/components/Login';
import Signup from './pages/auth/components/Signup';
import NotFound from './pages/notFound';

var routes = (
  <Router history={createBrowserHistory()}>
    <Route path="/" component={Application}>
    <IndexRoute component={Index} />
        <Route path="app" component={App} onEnter={ App.requireAuth } />
        <Route path="auth" component={Auth} />
            <Route path="signup" component={Signup} />
            <Route path="login" component={Login} />
        <Route path="*" component={NotFound} />
    </Route>
  </Router>
);

export default routes;

Thanks in advance for help.

like image 448
almccann Avatar asked Oct 28 '15 23:10

almccann


1 Answers

Take a look at the React Router server rendering guide again. You only render the <Router> with browser history on the client; on the server, you just pass the routes (but not the <Router>) to the <RoutingContext>.

like image 108
taion Avatar answered Sep 19 '22 17:09

taion