React Router example

Here I show a very simple and basic example of React Router to introduce routing in your application.

Step 1

Install create-react-app by running the command npm install create-react-app.

npm install create-react-app. 

Make sure that create-react-app is not installed globally. If it is installed globally make sure that it is uninstalled by running the command npm uninstall -g create-react-app. Otherwise you will face an error of missing script: start as mentioned here

Step 2

Now create your react app using below command. This will create new app called my-app.

npx create-react-app my-app

Step 3

Now change directory to your app and start your application.

cd my-app
npm start

This will start your app and you can see the application on your browser using link http://localhost:3000/

Step 4

Open the file App.js located in my-app/src and put the following content

import React from 'react';
import logo from './logo.svg';

import {
  BrowserRouter as Router,
} from "react-router-dom";

export default function App() {
  return (
              <Link to="/">Home</Link>
              <Link to="/about">About Me</Link>
              <Link to="/service">Services</Link>

        {/* A <Switch> looks through its children <Route>s and
            renders the first one that matches the current URL. */}
          <Route path="/about">
            <About />
          <Route path="/service">
          <Route path="/">
            <Home />

function Home() {
  return <h2>Holy Cow Home Page</h2>;

function About() {
  return <h2>I am Anil. An awesome react developer. :) </h2>;

function Services() {
  return <h2>I provide amazing services at a very high cost. </h2>;

You should see something like this in your browser.

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Leave a Reply

Your email address will not be published. Required fields are marked *