Skip to main content

Basic Navigation

You can read full guide and tutorial here

Navigation in React

Page creation

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, we will defined two paths "/" and "/about" when you direct to "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 />} />path define "/" path and render the <HomeHomePage /> 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

in ofHomePage.jsx Homeand elementAboutPage importwe Reactwill create a button a wrap with the Link component from "react"; import { Link } from "react-router-dom";dom

export

 default

function

HomePage.jsx

Home()

Route2.png

{

AboutPage.jsx

return

Route3.png

(

 <> <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.pngimage.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