Skip to main content

Basic Navigation

You can read full guide and tutorial here

Navigation in React

RoutesPage definecreation

In page folder, we will have two page Home page and About page

image.png

In each page we will create some button that can make us go to another page

 

 

 

In main.tsx file, youwe canwill desiredefined thetwo routepaths as you want. In this case there are 4 routes.

<BrowserRouter>
  <Routes>
    <Route path="*" element={<NoPage />} />
    <Route path="/" element={<Homeand />} />
    <Route path="/contact" element={<Contact />} />
    <Route path="/about" element={<Aboutwhen />}you />direct </Routes>to </BrowserRouter>
"localhost:5173/" , it will render the HomePage component and  when you direct to "localhost:5173/about", it will render the AboutPage component

 

Route1.png

<Route path="/" element={<Home />} /> define "/" path and render the <Home /> element

<Route path="/contact" element={<Contact />} /> define "/" path and render the <Contact /> element

<Route path="*" element={<NoPage />} /> When there is no path match will render<NoPage /> element because "*" means any path in URL

Links define.

When use click on Link element, it will tell the page to go to URL in "to={"/path"}"attribute

//example of Home element
import React from "react";
import { Link } from "react-router-dom";

export default function Home() {
  return (
    <>
      <div className="navbar">
        <div>
          <Link to={"/"} className="menu-link">
            Home
          </Link>
          <Link to={"/about"} className="menu-link">
            About
          </Link>
          <Link to={"/contact"} className="menu-link">
            Contact
          </Link>
        </div>
      </div>
      <div className="main">
        <h1>Home Page</h1>
      </div>
    </>
  );
}

When click at the about button, the page will render about page as we define in Route element in main.tsx

1706279643757.png1706279695430.png


**** createBrowserRouter, useNavigate and useLocation wil be soon updated

Here it is our basic navigation in React, next we will learn how to manage the dynamic route

Thanks to a good references :))))

https://medium.com/@pratya.yeekhaday/reactjs-ทบทวน-react-router-dom-v6-สำหรับ-typescript-ec1b7e3427b7