React Router is a popular library used for implementing page navigation and routing in React applications. By using React Router, you can create a seamless user experience with multiple page views while keeping your React components organised.
Adding React Router
To include React Router in your application, use the following command in your terminal from the root directory of the project:
npm install react-router-dom
Note: This tutorial uses React Router v7. To ensure the latest version is installed, you can use:
npm install react-router-dom@latest
Setting Up Folder Structure #
To create a multi-page application, organise your project files as follows:
src/
│
├── pages/
│ ├── Layout.js
│ ├── Home.js
│ ├── Blogs.js
│ ├── Contact.js
│ └── NoPage.js
Each file in the pages
folder will contain a React component representing a specific route.
Basic Usage #
Now, let’s integrate React Router in the main index.js
file:
Example Code
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 />);
Code Explanation
<BrowserRouter>
: Wraps the application to enable routing.<Routes>
: Defines the route structure.- Nested Routes:
- The
Layout
component is associated with the/
path. - Nested routes inherit the parent route; for example,
/blogs
becomes accessible throughLayout
.
- The
- Catch-All Route: The
*
path catches undefined routes and typically renders a 404 page.
Creating Page Components #
Layout.js
The Layout
component includes a navigation menu and an <Outlet>
where child routes are displayed.
import { Outlet, Link } from "react-router-dom";
const Layout = () => {
return (
<>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/blogs">Blogs</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
<Outlet />
</>
);
};
export default Layout;
Home.js
const Home = () => {
return <h1>Welcome to the Home Page</h1>;
};
export default Home;
Blogs.js
const Blogs = () => {
return <h1>Blog Articles</h1>;
};
export default Blogs;
Contact.js
const Contact = () => {
return <h1>Contact Us</h1>;
};
export default Contact;
NoPage.js
const NoPage = () => {
return <h1>404 - Page Not Found</h1>;
};
export default NoPage;
Want to learn React with an instructor, either offline or online? Find experienced tutors near you and join Coaching Wallah—completely free for students!
Leave your comment