Day 5: React Layouts, Outlets, and Links
On the fifth day of learning react, we grabbed on concepts like layouts, outlets, and links in React. They are essential concepts for structuring and navigating through a React application.
Layouts
These provide a consistent structure and design across multiple pages or views, enhancing user experience and maintaining visual coherence throughout the application. Layouts structure or design our application. They often include common components such as headers, footers, navigation menus, and sidebars that remain consistent across multiple pages or views of your application.
//MyRoute.js
import { BrowserRouter as Router, Routes, Route} from "react-router-dom"
import HomePage from "./pages/HomePage"
import AboutPage from "./pages/AboutPage"
import MainLayout from "./layouts/MainLayout"
import { ServicePage } from "./pages/ServicesPage"
import { ContactPage } from "./pages/ContactPage"
const MyRoutes = () => {
return(
<Router>
<Routes>
<Route path="/" element={<MainLayout/>} >
<Route path="/" element={<HomePage/>} />
<Route path="/about" element={<AboutPage/>}/>
<Route path="/services" element={<ServicePage/>}/>
<Route path="/contact" element={<ContactPage/>}/>
</Route>
</Routes>
</Router>
)
}
export default MyRoutes
Outlets
These offer a dynamic way to inject content into specific areas of the layout based on the current route or view, enabling flexible and modular application architecture. They provide a placeholder or target for dynamically injecting content based on the current route or view.
//MainLayout.js
import { Outlet } from "react-router-dom"
import { Footer } from "../components/footer/Footer"
import { Navbar } from "../components/navbar/Navbar"
const MainLayout = () =>{
return(
<>
<Navbar/>
<Outlet/>
<Footer/>
</>
)
}
export default MainLayout
Links
They facilitate seamless navigation within the application without the need for full page reloads, resulting in faster and smoother user interactions, thereby enhancing overall usability and user satisfaction. React provides the <Link> component from the react-router-dom package for handling client-side routing without a page reload.
import { Link } from 'react-router-dom';
import './Navbar.css'
export function Navbar() {
return (
<>
<nav className="navbar">
<div className="brand">Logo</div>
<ul className="items">
<li>
<Link to="/" className='nav-links'>Home</Link>
</li>
<li>
<Link to="/about" className='nav-links'>About</Link>
</li>
<li>
<Link to="/services" className='nav-links'>Services</Link>
</li>
<li>
<Link to="/contact" className='nav-links'>Contact</Link>
</li>
</ul>
</nav>7
</>
);
}
I am extending my gratitude to Bikash Karki for his insightful lectures.