How To Add React Router To Create React App

Share:
Source Code

If you want to add single page app capability to Create React App, then you need to add React Router to the project.  In this tutorial I will show you how you can do that quickly and painlessly.

We will start a simple seed project with create-react-app command:

create-react-app CRARouter

(If you need an intro or refresher on how Create React App works, then I suggest you check out this tutorial: Getting started with React with Create React App)

We need to first install React Router:

npm install react-router --save

Next we’re going to create a pages folder to house our routes, one folder per route, so for instance, this is what pages/Contact/Contact.js looks like:

import React, { Component } from 'react';
import './Contact.css';

class Contact extends Component {
 render() {
   return (
     <div className="Contact">
       <h1>Contact Page</h1>
     </div>
   );
 }
}
export default Contact;

Do the same for NotFound component that will serve as our 404 component.

In the src folder, create a routes.js:

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

import App from './App';
import Contact from './pages/Contact/Contact';
import NotFound from './pages/NotFound/NotFound';

const Routes = (props) => (
 <Router {...props}>
   <Route path="/" component={App}>
       <Route path="/contact" component={Contact} />
       <Route path="*" component={NotFound} />
   </Route>
 </Router>
);
export default Routes;

This will next our Contact and NotFound pages under our App component.

Next we need to update our index.js to make sure it uses React Router to handle our application:

import React from 'react';
import ReactDOM from 'react-dom';
import { browserHistory } from 'react-router';

import Routes from './routes';

import './index.css';

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

And finally, we need to make sure App.js behaves like a single page app, by modifying the content of App-intro div like so:

<p className="App-intro">
         To get started, edit <code>src/App.js</code> and save to reload.
         <p><Link to="/home">Home</Link></p>

         <p><Link to="/contact">Contact</Link></p>

         <p><Link to="/notexist">Not Exist</Link></p>
         {this.props.children}
       </p>

And you’re all done!  I told you it was going to be quick and painless 🙂

Resources:

  • React Router: React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. Make the URL your first thought, not an after-thought.
  • Create React App: Create React apps with no build configuration.
Comments Or Questions? Discuss In Our Discord

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

More from PentaCode