Author: M Abo Bakar Aslam

Navigation Between Components

Before continuing this lesson, you can download the starting code using the links provided. This will help you run and understand all examples easily.

1. Installing React Router

React Router is used to navigate between different components in a React application.

To install it, run the following command in your terminal:

npm install react-router-dom

2. Example Code 1

Multiple components are connected using routes. Each component is displayed only when its corresponding URL is accessed.

You should following components. If you download starting-application provided by the author, then the application already have these all compponents.

The Navbar component contains navigation links for switching between pages.

Step 2.1. Updating Navbar Component for Navigation

Navigation between components is handled using:

Key Points

For demonstration purposes, both approaches are used.

Important Notes

// File: page.tsx located in app-name/src/componenet/Navbar/
 
import { Link } from "react-router-dom";
 
export default function page() {
  return (
    <div style={{ backgroundColor: "green", color: "white" }}>
        <Link to="/">Home</Link>
        <Link to="/diary">Diary</Link>
        <Link to="/login-user">Login</Link>
 
        <a href="/register-user">Register</a>
    </div>
  )
}

Step 2.2. Configuring Routes in App Component

To enable routing, the main component must be configured properly.

Required Steps

Each component will only be rendered when its route is accessed.

// File: App.tsx located in app-name/src/
 
import Header from "../src/components/Header/page"
import Navbar from "../src/components/Navbar/page"
import Footer from "../src/components/Footer/page"
 
import Home from "../src/pages/Home/page"
import Register from "../src/pages/Register/page"
import Login from "../src/pages/Login/page"
import Diary from "../src/pages/Diary/page"
 
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
 
export default function App() {
  return (
    <Router>
    <div style={{ backgroundColor: "black", padding: "5px" }}>
      <h1 style={{color: "white"}}>This is main componenet (App)</h1>
      <Header />
      <Navbar />
 
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/diary" element={<Diary />} />
        <Route path="/login-user" element={<Login />} />
        <Route path="/register-user" element={<Register />} />
      </Routes>
 
      <Footer />
    </div>
    </Router>
  );
}

3. Working of Routing

4. Best Practices