Search code examples
javascriptreactjswebpackreact-routerwebpack-hmr

React-router Webpack HMR. The root route must render a single element


I am trying to figure out how the react-router works inside the AppContainer when HMR is enable and stuck upon the following error. Can you please explain what the hack is going on?

Invariant Violation: The root route must render a single element

Index.js

import React from 'react';
import ReactDOM from 'react-dom';

import { AppContainer } from 'react-hot-loader';
// AppContainer is a necessary wrapper component for HMR

import Routes from './routes/index';
const MOUNT_APP = document.getElementById('root');

const render = () => {
  ReactDOM.render(
    <AppContainer>
      <Routes />
    </AppContainer>,
    MOUNT_APP
  );
};

render();

// Hot Module Replacement API
if (module.hot) {
  module.hot.accept('./routes/index', () => {
    render()
  });
}

The route file is:

import React from 'react';
import { Router, IndexRoute, browserHistory } from 'react-router';

import Home from './Home';
import SubView from './Sub';

const componentRoutes = {
  component   : Home,
  path        : '/',
  indexRoute  : SubView,
  childRoutes : [

  ]
}

const Routes = () => {
  return (
    <Router history={browserHistory} routes={componentRoutes} />
  );
};

export default Routes;

HomeView Component:

import React from 'react';

const HomeView = () => {
    <div>
      <h4>Welcome</h4>
    </div>
}

export default HomeView;

HomeView Route:

import HomeView from './components/SubView';

export default {
  component: HomeView
}

P.S: SubView is equal to HomeView.


Solution

  • You need to return one element from the component. Right now your component for HomeView looks like this:

    const HomeView = () => {
        <div>
          <h4>Welcome</h4>
        </div>
    }
    

    You need to return the markup instead of just put it in the function body like this:

    const HomeView = () => {
        return (
             <div>
                 <h4>Welcome</h4>
             </div>
        )
    }