< Previous: Adding a Root Route Using React Router and IndexRoute   Next: Time for a Test: Clickable Usernames >

Cleaning up Our Routes and Preparing for the Next Step

We're going to make a small change to the way our routes list is stored, then it's time for you to take on another task.

First things first: we're storing our list of routes inside index.js, which is fine when you're just getting started but sooner or later needs to be put somewhere else to make your app easier to maintain. Well, that time is now, so create a new file called routes.js in your src directory where index.js is.

We're going to move most of the routing code out from index.js and in to routes.js so that we have a clear separation of concerns. This also means splitting up the import lines: routes.js needs to know all our app's imports, whereas index.js doesn't.

Here's the new code for routes.js

src/routes.js

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

import App from './pages/App';
import List from './pages/List';
import Detail from './pages/Detail';

const routes = (
    <Route path="/" component={ App }>
        <IndexRoute component={ List } />
        <Route path="detail/:repo" component={ Detail } />
    </Route>
);

export default routes;

That imports only what it needs, then creates a constant containing the route configuration for our app, and exports that constant so that others can use it.

What remains in index.js is the basic router configuration and the main call to ReactDOM.render(). Over time, as your application grows, you'll probably add more to this file, but trust me on this: you'll definitely fare better if you keep your route configuration out of your main index.js file.

Here's the new code for index.js:

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, useRouterHistory } from 'react-router';
import { createHashHistory } from 'history';

import routes from './routes';

const appHistory = useRouterHistory(createHashHistory)({ queryKey: false })

ReactDOM.render(
    <Router history={appHistory} onUpdate={() => window.scrollTo(0, 0)}>
        {routes}
    </Router>,
    document.getElementById('app')
);

With that little clean up complete it's time for your first major challenge.

Buy the book for $10

Get the complete, unabridged Hacking with React e-book and take your learning to the next level - includes a 45-day no questions asked money back guarantee!

If this was helpful, please take a moment to tell others about Hacking with React by tweeting about it!

< Previous: Adding a Root Route Using React Router and IndexRoute   Next: Time for a Test: Clickable Usernames >

Copyright ©2016 Paul Hudson. Follow me: @twostraws.