Search code examples
reactjsreact-routerreact-routing

React Router - dynamic routing setup


I am sure I am missing something simple here but can't get my routes configured properly.

I get this error:

Warning: Failed prop type: The prop 'children' is marked as required in 'App', but its value is 'undefined'. in App (created by RouterContext) in RouterContext (created by Router) in Router

Here is my basic setup:

./index.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import {Router, browserHistory} from 'react-router';
import routes from './routes';

ReactDOM.render(
  <Router history={browserHistory} routes={routes}/>, document.getElementById('root'));

./routes/index.js

module.exports = {
  path: '/',
  component: require('../components/app'),
  indexRoute: require('./home')
};

./routes/home.js

module.exports = {
  getComponent(nextState, cb) {
    require.ensure([], (require) => {
      cb(null, require('../components/home'));
    });
  }
};

./components/app/index.jsx

import React, {PropTypes} from 'react';

const App = props => (
  <section>
    <h1>My App</h1>
    <section>{props.children}</section>
  </section>
);

App.propTypes = {
  children: PropTypes.node.isRequired
};

export default App;

./components/home/index.jsx

import React from 'react';

const Home = () => (
  <section>
    <h3>Home</h3>
  </section>
);

export default Home;

Solution

  • You need need to specify .default when requiring a file using export. Home will be undefined without it hence the error

    ./routes/home.js

    module.exports = {
        getComponent(nextState, cb) {
            require.ensure([], (require) => {
    
            // need to specify .default when requiring a file using export
            cb(null, require('../components/home').default);
            });
        }
    };