Multi-Page React Application

Setting Up React Router

  1. Introduction to Multi-Page Applications (MPAs):

    • Understanding the difference between Single Page Applications (SPAs) and MPAs.

    • Benefits of using MPAs in React: improved SEO, better organization, and scalability.

  2. Setting Up React Router:

  • Install React Router: $npm install react-router-dom

  • Import BrowserRouter and set up routing in App.jsx:

    import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
    import Home from './pages/Home';
    import About from './pages/About';
    import Contact from './pages/Contact';
    
    function App() {
      return (
        <BrowserRouter>
          <nav>  {/* Navigation Links */}
            <Link to="/">Home</Link> | <Link to="/about">About</Link> | <Link to="/contact">Contact</Link>
          </nav>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
          </Routes>
        </BrowserRouter>
      );
    }
    
    export default App;

3. Creating Components for Different Pages:

  • Create a pages folder with separate files: Home.jsx, About.jsx, and Contact.jsx.

  • Example of a simple Home.jsx component:

4. Adding Navigation:

  • Use the Link component from React Router to create navigation:

  • Include Navbar in App.jsx to provide consistent navigation if you want to use a separate Navbar component.

5. Handling 404 Errors:

  • Add a catch-all route to handle undefined paths:

6. Styling the Application:

  • Use Tailwind CSS or standard CSS to style your pages and navigation.

Explanation of Key Concepts:

  • React Router: A library for handling navigation in React applications. In this context, it provides client-side routing within the MPA structure, making navigation feel faster.

  • BrowserRouter: A component that creates a routing context.

  • Routes: A component that defines the set of routes for the application.

  • Route: A component that maps a specific URL path to a React component.

  • Link: A component for creating navigation links.

Last updated