< Previous: Introducing React Router   Next: Creating a Link Between Pages in React Router >

How to Add a New Route to React Router

All that work we just did is important, but sadly looks identical to end users – frustrating, huh? But that's OK, because it was important groundwork for what's coming now: we're going to add a new page for our homepage, then move what we have now to be /react.

So, create a new file inside src/pages called List.js and give it this basic content for now:

src/pages/List.js

import React from 'react';

class List extends React.Component {
    render() {
        return <p>This is the list page.</p>;
    }
}

export default List;

We're going to make it so that going to the homepage loads our List component, and going to /react loads our Detail component. To make this happen we need to add a new route, then move the existing one.

As a reminder, here is your current index.js file

src/index.js

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

import Detail from './pages/Detail';

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

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

Please add an import for the new List component you made a moment ago. If you're not sure, it should look like this:

src/index.js

import List from './pages/List';

Now we need to move our existing route so that it handles /react and make a new route to handle /, like this:

src/index.js

<Route path="/" component={ List } />
<Route path="/react" component={ Detail } />

That's it! You should be able to point your web browser at http://localhost:8080 to see "This is the list page", then point it at http://localhost:8080/#/react to see our old page.

That wasn't hard, right? Right. But neither was it very useful: we need a way for users to be able to select a GitHub repository to view, which means upgrading our List page…

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: Introducing React Router   Next: Creating a Link Between Pages in React Router >

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