How to setup a basic react router

In this article I am going to show you how to setup a basic router in react js.

Very first thing you need to install react-router-dom  in your project. using npm comand

Example:

npm i react-router-dom

 

Then import  BrowserRouter, Routes, Route and Link  from "react-router-dom"

 

Example:

import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

Now you can setup router in your component

Code Example:

import React from "react";
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
export default function App() {
  return (
    <BrowserRouter>
      <Link to="/about">About</Link>
      <Link to="/contact">Contact</Link>
      <Link to="/services">Login</Link>

      <Routes>
      <Route path="/" element={<Home></Home>}></Route>
        <Route path="/about" element={<About></About>}></Route>
        <Route path="/contact" element={<Contact></Contact>}></Route>
        <Route path="/services" element={<Services></Services>}></Route>
      </Routes>
    </BrowserRouter>
  );
}


const Home = () => {
  return <h1>This is home page</h1>;
};

const About = () => {
  return <h1>This is about page</h1>;
};

const Contact = () => {
  return <h1>This is contact page</h1>;
};

const Services = () => {
  return <h1>This is services page</h1>;
};

 

About Author

Photo

Hi, I am Mahbub Hasan
Software Engineer

I am very much interested to share my programming
and development knowledge with the people.I will try
to update my blog everyday with new technology inshallah.

Thank You

For Visiting My Blog.

Contact Me