Basic Navigation
You can read full guide and tutorial here
Basic Navigation in React
Page creation
In page folder, we will have two page Home page and About 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
path
define "/" path and render the <HomePage />
element
Links define.
When use click on Link element, it will tell the page to go to URL in "to={"/path"}"attribute
in HomePage.jsx and AboutPage we will create a button aand wrap with the Link component from react-router-dom
HomePage.jsx
AboutPage.jsx
When click at the about button, the page will render about page as we define in Route element in main.tsx
Nested route
Nested Routing is the general idea of coupling segments of the URL to component hierarchy and data.
We will the new route call "contact" which will render the ContactPage component, and define the nested route for the contact route. "phone" path which will render PhoneBox component and "profile" will render ProfileBox component.
Create ContactPage.jsx in pages folder and put this content
import { Link, Outlet } from "react-router-dom";
function ContactPage() {
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
height: "100vh",
width: "100vw",
backgroundColor: "black",
}}
>
<h1>Contact Page</h1>
<Outlet />
<div>
<Link to={"/"}>
<button>Go to home</button>
</Link>
<Link to={"/about"}>
<button>Go to about</button>
</Link>
</div>
</div>
);
}
export default ContactPage;
Also with the PhoneBox.jsx and ProfileBox.jsx in components folder
//ProfileBox.jsx
function ProfileBox() {
return <div>Profile</div>;
}
export default ProfileBox;
//PhoneBox.jsx
function PhoneBox() {
return <div>Phone</div>;
}
export default PhoneBox;
When you go to "/contact" you might only see the title Contact Page
But when you direct to "/contact/phone" it will show the text Phone under the contact page name
Explanation
path phone is the child of the contact path and if you notice something in ContactPage.jsx file, there is a component name <Outlet/>
in the code
An <Outlet>
should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.
In this example, we have an Outlet component in the ContactPage..jsx which is the parent element when we enter the URL that include their child component it will render a child component according to the route index.