Building a React.js App: Basic Routing with React Router

Share this video with your friends

Send Tweet

React Router is the most popular, and arguably the best solution for adding Routing to your React application. In this video, we’ll talk about the ideology around React Router as well as set up basic routing for our application.

Simon Davies
Simon Davies
~ 9 years ago

I was wondering if anyone has an idea or a link on animating these route transitions, eg instead of showing the next page immediately , so how fade the current then fade in the new view? I have looked at adding removing classes on the main views, using componentWillMount etc. but this does not work, its not like activating the transition but showing imediatley etc, thanks

Tyler McGinnis
Tyler McGinnis(instructor)
~ 9 years ago

Simon. I believe React Router 1.0 is going to add route change animations. They're a beta branch right now that you can checkout.

Ashwin
Ashwin
~ 9 years ago

What text editor are you using here?

Tyler McGinnis
Tyler McGinnis(instructor)
~ 9 years ago

Hi Ashwin, I'm using Sublime. All my settings can be found in this tweet. https://twitter.com/tylermcginnis33/status/610920794189889536

egghead eggo
egghead eggo
~ 9 years ago

The lesson video has been updated!

KKD GGC
KKD GGC
~ 9 years ago

Trying to run webpack -w and I am getting:

"Module build failed: ReferenceError: [BABEL] /home/karan/projects/react-tutorial/app/App.js: Unknown option: direct.presets". 

My webpack.config.js looks like the following:

module.exports = {
	entry: "./app/App.js",
	output: {
		filename: "public/bundle.js"
	},
	module:{
		loaders:[
			{
				test: /\.jsx?$/,
				exclude: /(node_modules|bower_components)/,
				loader: 'babel',
				query: {
					presets: ['react', 'es2015']
				}
			}
		]
	}
};

My package.json:

{
  "name": "react-tutorial",
  "version": "1.0.0",
  "description": "react tutorial",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "history": "^1.13.1",
    "react-dom": "^0.14.0",
    "react-router": "^1.0.1"
  },
  "devDependencies": {
    "babel-core": "^5.8.30",
    "babel-loader": "^5.3.2",
    "webpack": "^1.12.9"
  }
}

and I have no clue what I am doing wrong. I am not sure if I have the wrong version of any of the package described :(

Joel Hooks
Joel Hooks
~ 9 years ago

both the webpack config and package.json are provided in the lesson source. Have you compared with that?

KKD GGC
KKD GGC
~ 9 years ago

oh god, in routes.js, the problem was that I was using curly brace {} in module.exports instead of parenthesis (). noob alert!

Tyler McGinnis
Tyler McGinnis(instructor)
~ 9 years ago

:)

Maximilian Patan
Maximilian Patan
~ 9 years ago

This may be explained later on but I decided to name my component main instead of 'Main'. So...

var main = React.createClass... ... ReactDOM.render(<main/>, ...

This did not work. Had to use the upper case M. Why is that?

Joel Hooks
Joel Hooks
~ 9 years ago

This may help, it is a JSX convention: https://gist.github.com/sebmarkbage/f1f4ba40816e7d7848ad

Maximilian Patan
Maximilian Patan
~ 9 years ago

Interesting - thanks Joel.

Jessica Waite
Jessica Waite
~ 9 years ago

Thanks!!!

Daniel Pazuchowski
Daniel Pazuchowski
~ 9 years ago

Just in-case anyone gets stuck like I did. I was receiving an error in the dev console stating "React.createElement: type should not be null, undefined, booolean, or number".

The issue is in the way we instantiate our react-router. Instead of var Route = Router.route, I needed to either use import { Route } from 'react-router' or var Route = require('react-router').Route. I was then able to view pages correctly.

fannarx
fannarx
~ 9 years ago

(y) Worked for me.

Sky
Sky
~ 9 years ago

If you are following along and are having issues, make sure that you are exporting Home.js (it took me too long to realize that was my issue!)

Marciano
Marciano
~ 9 years ago

Hi there,

I'm running against problems with React-router. Not sure why exactly. But this is the warning I get: Warning: [react-router] Routerno longer defaults the history prop to hash history. Please use thehashHistory singleton instead. http://tiny.cc/router-defaulthistory

I'm not sure what to do about this. I checked out this url: https://github.com/rackt/react-router/blob/master/upgrade-guides/v2.0.0.md

But this doesn't help me to get along. Does anyone know what I need to do?

Thanks.

Tyler McGinnis
Tyler McGinnis(instructor)
~ 9 years ago

Hi Marciano,

You probably downloaded the latest Router and not the one downloaded in the video. With React Router 2.0 they, as the error mentioned, no longer use hashHistory by default when they instantiate the Router. Basically that means <Router> becomes

<Router history={hashHistory} />```

see more here https://github.com/rackt/react-router/blob/master/upgrade-guides/v2.0.0.md#no-default-history
Gee Jay Almestas
Gee Jay Almestas
~ 9 years ago

Hi, i'm kind of confuse when i tried to view the index.html i didn't see anything, it doesn't gives me an error in the console also even doing webpack -w everything is fine... can you guys look at my files if i did something wrong?

here's my git files https://jigsgfx@bitbucket.org/jigsgfx/egghead-react.git

do you think is it because i don't have a package.json? why because when i install the package it didn't gives a package.json

EDIT: ok my bad i did a typo error on routes.js

what i did is instead of "component" i made it "componnent" with double "n" :D

BP Mishra
BP Mishra
~ 9 years ago

Thanks!

Jin
Jin
~ 9 years ago

when I try to run the app, it renders OK, but in the console I am getting this warning: "Warning: [react-router] Router no longer defaults the history prop to hash history. Please use the hashHistory singleton instead. http://tiny.cc/router-defaulthistory"

Jin
Jin
~ 9 years ago

ok, it's because react-router wont create a default history since version 2, https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#no-default-history

you need to provide it by yourself

Tyler McGinnis
Tyler McGinnis(instructor)
~ 9 years ago

Correct. React Router is constantly changing. In the video we're on 1.0 but they're on 2.0 already (3 months later, sigh). They've committed to support 1.0 until 3.0 is out. So once 3.0 drops I'll update the videos again.

Jin
Jin
~ 9 years ago

the nested routing in this example could cause problems, instead of going to the child Route, it always render the {Main}, solved by doing something like this:

<Route name='app'> <Route path='/' component={Main} /> <Route path='profile/:username' component={Profile} /> <IndexRoute component={Home} /> </Route>
Joe Maiers
Joe Maiers
~ 9 years ago

Excellent! You just saved me hours most likely. :)

Bharat Soni
Bharat Soni
~ 9 years ago

In App.js file I was adding spaces around {routes} this line <Router history={hashHistory}>{routes}</Router>. Which caused me 2 errors in console:

Warning: Failed propType: Invalid prop `children` supplied to `Router`.
Warning: [react-router] Location "/" did not match any routes

Just in case if anybody else is getting the same error.

Calvin Rachuy
Calvin Rachuy
~ 8 years ago

Same

Ash
Ash
~ 8 years ago

Thanks mate. It helped me.

Niccolo Perra
Niccolo Perra
~ 8 years ago

It's not shown in the video somehow, but in Home.js don't forget to do module.exports = Home; if not then the Home will never show!

Glenn
Glenn
~ 8 years ago

I foolishly npm installed the latest versions of everything so ran into the issues other have mentioned regarding no default history. It didn't prevent my code from running but the error was annoying.

hashHistory needs to be called on

var React = require('react-router'); 

... as against on

var React = require('react-router').Router;

This confused me a little so I broke ReactRouter out as you can see below:

App.js:

var React = require('react');
var ReactDOM = require('react-dom');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var hashHistory = ReactRouter.hashHistory;
var routes = require('./config/routes');

ReactDOM.render(
  <Router history={hashHistory}>
    {routes}
  </Router>,
  document.getElementById('app')
)

I learnt more about React from using the latest version so I hope that helps someone else. It doesn't help that React's documentation is all in ES6.

Rolando Barbella
Rolando Barbella
~ 8 years ago

If you are using react-router v2+ with ES6, in the route.js, you need to import the file like this

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

In the App.js do this:

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

and

<Router history={browserHistory}>{routes}</Router>,
document.getElementById('app')
Reactor
Reactor
~ 8 years ago

There are actually curly braces in transcript ;) This way it works:

routes = (
  <Route path="/" component={Main}>
  </Route>
);

module.exports = routes;
Fisker Karma
Fisker Karma
~ 8 years ago

You just saved me a lot of time! Thanks :)

Rajaprabhakaran
Rajaprabhakaran
~ 8 years ago

I followed the lesson and when I opened index.html, I have an error in the output bundle.js

var history = this.props.history;

this.props.history is undefined.

I have installed the current version of react and its deps. May be the code and lesson are not compatible with current version. ?

Rachel
Rachel
~ 8 years ago

I realize this error may be because I accidentally installed the current version of everything but I keep getting a weird error in the console (see below). Anyone have any ideas? Here's my github repository for the project if that helps https://github.com/noeladd/egghead-react

bundle.js:22102 Uncaught TypeError: Cannot read property 'getCurrentLocation' of undefined(…)createTransitionManager @ bundle.js:22102Router_componentWillMount @ bundle.js:22109(anonymous function) @ bundle.js:15390measureLifeCyclePerf @ bundle.js:15117performInitialMount @ bundle.js:15389mountComponent @ bundle.js:15300mountComponent @ bundle.js:7757performInitialMount @ bundle.js:15413mountComponent @ bundle.js:15300mountComponent @ bundle.js:7757mountComponentIntoNode @ bundle.js:20540perform @ bundle.js:8750batchedMountComponentIntoNode @ bundle.js:20562perform @ bundle.js:8750batchedUpdates @ bundle.js:17620batchedUpdates @ bundle.js:7412_renderNewRootComponent @ bundle.js:20756_renderSubtreeIntoContainer @ bundle.js:20837render @ bundle.js:20858(anonymous function) @ bundle.js:54__webpack_require__ @ bundle.js:20(anonymous function) @ bundle.js:40(anonymous function) @ bundle.js:43

Kacper Myslinski
Kacper Myslinski
~ 8 years ago

+1

Alvin
Alvin
~ 8 years ago

Working through this when the code is out of date caused me so much pain!

Jen
Jen
~ 8 years ago

if you are copying the code from the transcript be aware that: module.exports = { <Route path="/" component={Main}> </Route> }; should be: module.exports = ( <Route path="/" component={Main}> </Route> );

Jen
Jen
~ 8 years ago

Thanks!

Andrew
Andrew
~ 8 years ago

Can anyone tell me what's going on? I've combed over the code meticulously, and can't find anything different from what was in the video:

After adding routes, nothing renders on the page, and I'm getting the following error when running webpack -w

ERROR in ./app/App.js Module not found: Error: Can't resolve './config/routes' in >'/Users/andrewsmith/Desktop/egghead_react_notetaker/app' @ ./app/App.js 6:13-39

App.js

var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router').Router;
var routes = require('./config/routes');

ReactDOM.render(
// Retrieve the <Route></Route> from config/routes.js
  <Router>{routes}</Router>,
  document.getElementById('app')
)

routes.js

var React = require('react');
var Main = require('../components/Main');
var Home = require('../components/Home');
var Profile = require('../components/Profile');
var Router = require('react-router');
var Route = Router.Route;
var IndexRoute = Router.IndexRoute;

// Exporting the instruction for our router to App.js.
module.exports = (
  // Going to the root path of the application will result in being served the Main component.
  // IndexRoute is a default path, used if no other routes match.
  <Route path="/" component={Main}>
    <Route path="profile/:username" component={Profile} />
    <IndexRoute component={Home} />
  </Route>
);