React-router multiple routes (React components)

735 views Asked by At

Below are my routes.js that handles every request - this is for server side rendering in react - I have the following 2 files - I get hello world right now The main issue I have is - Where do i handle other routes? I am confused here this part - how do I make base.js with static <!Doctype><head><title></head> - but with different components like /about & /other depending upon the request url? please help me with this - this feels like a big road block for me - have been trying many examples but everything seems so complicated -

routes.js

var express = require('express');
var router = express.Router();
import React, { Component } from 'react';
import ReactDOMServer from 'react-dom/server';
var ReactRouter = require('react-router');
import { renderToString } from 'react-dom/server';

router.get('*', function(request, response) {
    ReactRouter.match({
        routes: (
            <ReactRouter.Router history={ReactRouter.browserHistory}>
                <ReactRouter.Route path='/' component={require('./src/Components/layout/base')}>
                </ReactRouter.Route>
            </ReactRouter.Router>
        ),
        location: request.url
    }, function(error, redirectLocation, renderProps) {
        if (renderProps) {
            var html = ReactDOMServer.renderToString(
                <ReactRouter.RouterContext {...renderProps} />
            );
            response.send(html);
        } else {
            response.status(404).send('Not Found');
        }
    });
});

module.exports = router;

base.js

var React = require('react');
    module.exports = React.createClass({
        render: function() {
            return React.createElement('h1', null, 'Hello World!');
        }
    });
1

There are 1 answers

0
James Gentes On

You'll need to use {this.props.children} within your base component. Here's an example:

import Header from './Header';
import React from 'react';

class Base extends React.Component {

  render() {
    return (
      <div>
        <Header />
        <div>
          {this.props.children}
        </div>
      </div>
    );
  }
}

export default Base;

Then you can create a sub-route within the base route you already have:

<ReactRouter.Route path='/' component={require('./src/Components/layout/base')}>

  <ReactRouter.Route path='/awesome-page' component={require('./src/Components/layout/awesome-page')}>
  </ReactRouter.Route>

</ReactRouter.Route>