[React.js] - Part 8. React Router

Ace Lennox
2025年01月20日読了時間:3分

React Router is the most popular library for handling routing in React applications. This guide walks you through setting up and using React Router with a clear structure and examples.


1. Adding React Router

Install React Router by running the following command in your terminal:

npm install react-router-dom

If you are upgrading from an older version (e.g., v5), use the @latest flag:

npm install react-router-dom@latest

This guide uses React Router v6.


2. Setting Up the Folder Structure

To create a multi-page application, structure your files as follows:

src/
  pages/
    Layout.js
    Home.js
    Blogs.js
    Contact.js
    NoPage.js

Each file will contain a simple React component.


3. Basic Setup in index.js

Now, configure React Router in your index.js file to handle routing between pages:

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";

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 />);

4. How It Works

  1. <BrowserRouter>: Wraps the application, enabling React Router to manage navigation.

  2. <Routes>: Defines all the possible routes.

  3. <Route>: Specifies the path and the component to render.

    • The path="/" route renders the Layout component.

    • Nested routes like path="blogs" become /blogs when combined with the parent route.

  4. Default Route: <Route index element={<Home />}> acts as the default route for /.

  5. 404 Page: The path="*" route catches all undefined URLs, useful for a 404 page.


5. Creating Pages

Layout Component

The Layout component is a shared wrapper for all pages. It includes navigation links and an <Outlet> to render the selected route.

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;

Other Pages

Here are simple components for the pages:

Home.js

const Home = () => {
  return <h1>Welcome to the Home Page</h1>;
};

export default Home;
 

Blogs.js

const Blogs = () => {
  return <h1>Our Blog Posts</h1>;
};

export default Blogs;

Contact.js

const Contact = () => {
  return <h1>Get in Touch</h1>;
};

export default Contact;

NoPage.js

const NoPage = () => {
  return <h1>404 - Page Not Found</h1>;
};

export default NoPage;
 

6. Navigation

React Router uses <Link> instead of <a href=""> for navigation. This keeps the app’s state intact and avoids full page reloads.

For example:

<Link to="/">Home</Link>
<Link to="/blogs">Blogs</Link>
<Link to="/contact">Contact</Link>
 

Summary

With React Router, you can create dynamic, multi-page applications easily. Here's what we covered:

  1. Install React Router using npm.

  2. Set up a clear folder structure for pages.

  3. Configure routing in index.js.

  4. Use <Routes> and <Route> for navigation.

  5. Use <Link> for internal navigation.

  6. Handle undefined routes with a catch-all 404 page.

Try these examples to get started with routing in React!


Source Code

The complete source code for this project is available on GitHub


最近の投稿

Latest Posts


logo

プログラミング、ウェブ開発、モバイルアプリ作成に関する洞察的な記事とチュートリアルを探索します。ReactJS、Next.js、Android、iOS、および最新のコーディングプラクティスについて学びます。実践的な例と、アプリケーションを構築するためのヒントを学びます。すべてのレベルの開発者がスキルを向上させるための理想的な場所です。

SNS

© 2025. All rights reserved