React Router Step By Step Tutorial

In this tutorial, we will learn how to configure step by step routing in the ReactJS application.

React is an open-source JavaScript library for building single-page applications.

If you are a beginner and want to learn ReactJS then check out ReactJS Tutorial for Beginners

We will use the react-router-dom package to configure routing in the React app.

The react-router-dom is a specific library for handling routes within a web app. At its core, what React Router does is conditionally render certain components to display depending on the route being used in the URL (/ for the homepage).

Why use React router? It allows you to build single-page web applications (SPA) with navigation. React Router uses component structure to call components, which display the appropriate information. React router also allows the user to utilize browser functionality like the back button, and then refresh the page, all while maintaining the correct view of the application.

Steps to Configure Routing in React App

  1. Create React App
  2. Install a React Router
  3. Create React Class Components
  4. Configure Routing in App Component
  5. Demo

1. Create React App

Let's create a new React app using create-react-app CLI tool.

The Create React App CLI tool is an officially supported way to create single-page React applications. It offers a modern build setup with no configuration.

Let's use the below command to quickly create and setup React app:

npx create-react-app react-routing-tutorial

2. Install a React Router

To use React Router, you first have to install it using NPM:

npm install react-router-dom

Once the react-router-dom package installed then entry will be added to the package.json file in the dependencies section:

{
  "name": "react-helloworld-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

3. Create React Class Components

To demonstrate routing in React, we first need to create a few react components.

We will create four React class components:

  • Home
  • About
  • Contact
  • Services

The App component will be used as a tab menu. The other four components (Home), (About), (Contact), and (Services) are rendered once the route has changed.

Home

Let's create a Home.js file and add the following code to it:

import React, { Component } from 'react'

class Home extends Component {
    constructor(props) {
        super(props)

        this.state = {
                 title: 'Home Page'
        }
    }

    render() {
        return (
            <div>
                <h1> {this.state.title } </h1>
            </div>
        )
    }
}
export default Home

This component very simple and just displays the title on the web page.

About

Let's create an About.js file and add the following code to it:

import React, { Component } from 'react'

class About extends Component {
    constructor(props) {
        super(props)
    
        this.state = {
            title: 'About Page'            
        }
    }
    
    render() {
        return (
            <div>
                <h1>{this.state.title}</h1>
            </div>
        )
    }
}

export default About

This component very simple and just displays the title on the web page.

Contact

Let's create a Contact.js file and add the following code to it:

import React, { Component } from 'react'

export default class Contact extends Component {
    constructor(props) {
        super(props)

        this.state = {
            title: 'Contact Page'                 
        }
    }

    render() {
        return (
            <div>
                <h1> {this.state.title }</h1>
            </div>
        )
    }
}

This component very simple and just displays the title on the web page.

Services

Let's create a Services.js file and add the following code to it:

import React, { Component } from 'react'

export default class Services extends Component {
    constructor(props) {
        super(props)

        this.state = {
                 title: "Services Page"
        }
    }

    render() {
        return (
            <div>
                <h1> {this.state.title } </h1>
            </div>
        )
    }
}

This component very simple and just displays the title on the web page

4. Configure Routing in App Component

You'll need to import BrowserRouter, Route, Link, and Switch elements from the react-router-dom package:

import { BrowserRouter as Router, Route, Switch,Link } from 'react-router-dom';

Now open the App component and add the following routing code to it:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route, Switch,Link } from 'react-router-dom';
import Home from './components/Home';
import Services from './components/Services';
import About from './components/About';
import Contact from './components/Contact';

function App() {
  return (
    <Router>
    <div>
          <h2>React Router Tutorial for Beginners</h2>
          <nav>
          <ul>
            <li><Link to={'/'} > Home </Link></li>
            <li><Link to={'/contact'} >Contact</Link></li>
            <li><Link to={'/about'} >About</Link></li>
            <li><Link to={'/services'} >Services</Link></li>
          </ul>
          </nav>
          <Switch> 
                <Route path = "/" exact component = {Home}></Route>
                <Route path = "/contact" component = {Contact}></Route>
                <Route path = "/about" component = {About}></Route>
                <Route path = "/services" component = {Services}></Route>
          </Switch>
    </div>
    </Router>
  );
}

export default App;

Note that we have provided the Router as an alias to the BrowserRouter module. 

We have added the Switch element (open and closing tags). These ensure that only one component is rendered at a time.

          <Switch> 
                <Route path = "/" exact component = {Home}></Route>
                <Route path = "/contact" component = {Contact}></Route>
                <Route path = "/about" component = {About}></Route>
                <Route path = "/services" component = {Services}></Route>
          </Switch>

We have defined <Route> tags inside the <Switch> tag to configure the route with its components.

In this <Route> tag, we simply add a path attribute and the name of the component you want to load with component attribute.

                <Route path = "/" exact component = {Home}></Route>
                <Route path = "/contact" component = {Contact}></Route>
                <Route path = "/about" component = {About}></Route>
                <Route path = "/services" component = {Services}></Route>

We have used Link for each component in the app and use to="URL" to link them:

<nav>
       <ul>
            <li><Link to={'/'} > Home </Link></li>
            <li><Link to={'/contact'} >Contact</Link></li>
            <li><Link to={'/about'} >About</Link></li>
            <li><Link to={'/services'} >Services</Link></li>
       </ul>
</nav>

5. Demo

Let's run the React app using the below command:

npm start

Runs the app in development mode. Open http://localhost:3000 to view it in the browser.

When the app is started, we will see four clickable links that can be used to change the route:

Related React Tutorials and Examples

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments