#react #tutorial #advanced

Day 8: Routing with React Router

Day 8: Routing with React Router

React helps us build Single Page Applications (SPAs). In an SPA, you don’t reload the page when you click a link. Instead, JavaScript swaps the content.

We use React Router (specifically react-router-dom) to handle this.

Installation

npm install react-router-dom

Basic Setup

Wrap your app in BrowserRouter and define your Routes.

// main.jsx
import { BrowserRouter } from 'react-router-dom';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);
// App.jsx
import { Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';

function App() {
  return (
    <div>
      <nav>
        {/* Use Link instead of <a href> to prevent page reload */}
        <Link to="/">Home</Link> | <Link to="/about">About</Link>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </div>
  );
}

Dynamic Routes

What if we want a profile page like /user/jack or /user/jill? We use URL Parameters.

// App.jsx
<Route path="/user/:username" element={<UserProfile />} />

Inside the component, use useParams to read the value.

// UserProfile.jsx
import { useParams } from 'react-router-dom';

function UserProfile() {
  const { username } = useParams();
  return <h1>Profile for: {username}</h1>;
}

Sometimes you need to navigate after an action (like submitting a login form), not just clicking a link. Use useNavigate.

import { useNavigate } from 'react-router-dom';

function Login() {
  const navigate = useNavigate();

  function handleLogin() {
    // ... logic ...
    navigate('/dashboard'); // Redirect user
  }
}

404 Not Found

To handle unknown routes, add a “catch-all” route at the end.

<Route path="*" element={<NotFoundPage />} />

Homework for Day 8:

  1. Create a multi-page Portfolio app.
  2. Pages: Home, Projects, Contact.
  3. Create a ProjectDetail page (/projects/:id) that shows details based on the an ID.
  4. Add a shared Navbar that stays visible on all pages.

Next up, Day 9: Leveling up with Custom Hooks!