React JS App: router
ReactJS router
1 Overview
📘 router Create React App
doesn’t include page routing. React Router
is the most popular solution. It allows you to define routes for different parts of your application and to programmatically navigate between them.
2 Install
3 Folder tree
To create an application with multiple page routes, let’s first start with the file structure.
Within the src
folder, we’ll create a folder named pages
with several files:
index.js
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="blogs" element={<Blogs />} />
<Route path="contact" element={<Contact />} />
<Route path="*" element={<NoPage />} />
</Route>
</Routes>
</BrowserRouter>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
The Layout component has <Outlet>
and <Link>
elements. The <Outlet>
renders the current route selected. <Link>
is used to set the URL and keep track of browsing history.
Anytime we link to an internal path, we will use <Link>
instead of <a href="">
. The layout route is a shared component that inserts common content on all pages, such as a navigation menu.
Layout.js