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 https://github.com/facebook/create-react-app/issues/8086
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,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About Me</Link>
</li>
<li>
<Link to="/service">Services</Link>
</li>
</ul>
</nav>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/service">
<Services/>
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}
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.
