Alex
Alex

Reputation: 749

React router dynamic routes not rendering component

I’m trying to get react router dynamic routing to work by following this example: https://github.com/rackt/react-router/tree/master/examples/huge-apps

Here’s my setup:

webpack.config.js:

module.exports = {
  devtool: 'inline-source-map',
  entry: './js/app.js',
  output: {
    path: '../public',
    filename: 'test-app.js',
    chunkFilename: '[id].chunk.js',
    publicPath: '/public/'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: [
            'es2015',
            'react'
          ]
        }
      }
    ]
  }

./js/app.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { createHistory, useBasename } from 'history';
import { Router } from 'react-router';

const history = useBasename(createHistory)({
  basename: '/'
});

const rootRoute = {
  component: 'div',
  childRoutes: [{
    path: '/',
    component: require('./components/App')
  }]
};

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

./components/App.js:

import React from 'react';

console.log('testing');

export default class App extends React.Component {
  render() {
    console.log('App');
    return (
        <div>
          App!
        </div>
    )
  }
}

index.html:

<!doctype html>
<html>
    <head>
        <title>Test App</title>
    </head>
    <body>
        Hello
        <div id="root"></div>
        <script src="public/test-app.js"></script>
    </body>
</html>

When I run the server, I see Hello displayed from index.html, I also see console.log('testing') from App.js, but the actual App.js component does not render. Any ideas why?

Thanks!

EDIT: If I change ./components/App.js to ES5 syntax below, it works! Why is that? Does react router's component: require('./components/App') not work with ES6?

var React = require('react');

var App = React.createClass({
  render: function() {
    return (
      <div>
        App!
      </div>
    )
  }
});

module.exports = App;

Upvotes: 2

Views: 3422

Answers (1)

Vlad Shcherbin
Vlad Shcherbin

Reputation: 108

I think, you are using Babel 6, where they changed commonjs require syntax.

Now, you need to add the default:

component: require('./components/App').default

I had the same problem, finally found how to make it work.

Upvotes: 5

Related Questions