React Router V4
UI Development

Routing with React Router v4.0

What is this blog about?

Some of the material on web is pretty confusing, there hasn’t been clear distinction as to which version the material refers to. This blog is intended for those who understand React and are using the react router v4.0 for the first time.
Lets create a simple navigation (assuming you have set up the environment and are ready to write main.js)

Why version 4.0 ?

Routing with React Router version 4.0 is to be noted because there have been considerable changes made compared to previous versions of React Router. Following the old way of routing with React Router v3.0 or earlier seems to cause errors.

These are some of the problems that you might encounter :

  • Warning: React.createElement: type is invalid — expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in.
  • Warning: Failed prop type: The prop history is marked as required in Router, but its value is undefined in Router.
  • Uncaught TypeError: Cannot read property ‘location’ of undefined at new Router.

Why are these problems caused ?

These problems are caused because some of the modules required by React Router v3.0 or lower are not available in React Router v4.0 and older way of routing is no longer supported in React Router v4.0.

This is how it goes with version v3.0 :

Changes to be Made:

One of the major changes include importing from ‘react-router-dom’ instead of ‘react-router’. Before this ‘react-router-dom’ package should be installed. Instead of importing ‘Router’ the ‘BrowserRouter as Router’ is imported. Also there is no need to import ‘browserHistory’ and ‘IndexRoute’. Because of introduction of ‘exact’ the ‘IndexRoute’ is not neccessary.

This is how the code goes with React Router v4.0 :

Notice above that instead of classes ‘const’ is used. Note that this is not necessary , we can still use classes to define components. Also we are using ‘BrowserRouter’ here by choice. BrowserRouter, NativeRouter, StaticRouter, HashRouter, and MemoryRouter are all available to suit your requirements.
One other major change to note is that Routes are included in the component where their respective Route Components needs to rendered and there is no use of {this.props.children}. Hence we dont nest routes anymore.

For a live demo of React Router v4.0 go to this codepen link  .

Need help with your website? Reach us at Techaspect .

About The Author

Leave a Reply

*