Navigate in ReactJS using React V4 Router

If you are building a large single page application, there might come a time when you will need to add routes to different pages. Unlike traditional routes, adding routes in ReactJS does not trigger a page reload. This makes your SPA extremely fast and feels more like an actual application rather than a simple website. To navigate in ReactJS we will be using the React v4 router.

Setting Up React V4 Router

Begin by installing the React V4 Router from npm:

npm install --save react-router-dom

Now, in your index.js you will need to import BrowserRouter and wrap it around your main App component. The reason for doing this is so that you will not have to manually pass the routes down to each component; this automatically sets that up for you.

//The usual imports above
import { BrowserRouter } from 'react-router-dom';
<App />
</BrowserRouter>, document.getElementById('root'));

ReactJS Router Switch

Now it’s time to setup where you want each rendered route to be at. The simple solution is to use the switch component from react-router-dom. The switch component allows you to change render a different view in the component you place it in. So I am going to add the following in my App.js

import { Switch, Route } from 'react-router-dom';
import ScreenA from './components/ScreenA';
import ScreenB from './components/ScreenB';

class App extends Component {
render() {
return (
<Route exact path="/" component={ScreenA} />
<Route path="/b" component={ScreenB} />

I first imported the Switch and rotue components. I also created two other components called Screen A and B. Finally, in my render function I set the default route to go to ScreenA and if the path match /b component will switch to ScreenB.

Here’s my ScreenA.js:

import React from 'react'
import { Link } from 'react-router-dom'
const ScreenA = () =>(
<h1>This is screen A</h1>
<li><Link to='/b'>Go to screen B</Link></li>

export default ScreenA;

Here’s my ScreenB.js:

import React from 'react'
import { Link } from 'react-router-dom'
const ScreenB = () => (
<h1>This is screen B</h1>
<li><Link to='/'>Go to Screen A</Link></li>

export default ScreenB;

And the final result is this:

View code on GitHub