Zum Inhalt springen
React Anfänger 25 min

Navigation & Links

Vertiefe dein Wissen über Navigation in React. Lerne Breadcrumbs, aktive Links, Redirects und fortgeschrittene Routing-Patterns.

Aktualisiert:

Navigation & Links

Im vorherigen Kapitel hast du die Grundlagen von React Router gelernt. Jetzt vertiefen wir das Thema Navigation – von aktiven Links ueber Breadcrumbs bis hin zu Redirects und Scroll-Verhalten.

Aktive Navigation gestalten

import { NavLink } from 'react-router-dom';
import styles from './Navigation.module.css';

function MainNav() {
  const links = [
    { to: '/', label: 'Home' },
    { to: '/products', label: 'Produkte' },
    { to: '/about', label: 'Ueber uns' },
    { to: '/contact', label: 'Kontakt' }
  ];

  return (
    <nav className={styles.nav}>
      {links.map(link => (
        <NavLink
          key={link.to}
          to={link.to}
          end={link.to === '/'}
          className={({ isActive }) =>
            `${styles.link} ${isActive ? styles.active : ''}`
          }
        >
          {link.label}
        </NavLink>
      ))}
    </nav>
  );
}

Die end-Prop

Standardmaessig ist ein NavLink aktiv, wenn die URL mit dem to-Pfad beginnt. Die end-Prop aendert das:

// Ohne end: "/" ist IMMER aktiv (jede URL beginnt mit /)
<NavLink to="/">Home</NavLink>

// Mit end: "/" ist nur aktiv bei exakter Uebereinstimmung
<NavLink to="/" end>Home</NavLink>

Breadcrumbs zeigen dem User, wo er sich in der App befindet:

import { useLocation, Link } from 'react-router-dom';

function Breadcrumbs() {
  const location = useLocation();
  const pathnames = location.pathname.split('/').filter(Boolean);

  const labels = {
    products: 'Produkte',
    about: 'Ueber uns',
    contact: 'Kontakt',
    settings: 'Einstellungen'
  };

  return (
    <nav style={{ padding: '0.5rem 0', fontSize: '0.9rem', color: '#666' }}>
      <Link to="/" style={{ color: '#3498db', textDecoration: 'none' }}>
        Home
      </Link>
      {pathnames.map((segment, index) => {
        const path = `/${pathnames.slice(0, index + 1).join('/')}`;
        const isLast = index === pathnames.length - 1;
        const label = labels[segment] || segment;

        return (
          <span key={path}>
            <span style={{ margin: '0 0.5rem' }}>/</span>
            {isLast ? (
              <span style={{ fontWeight: 'bold' }}>{label}</span>
            ) : (
              <Link to={path} style={{ color: '#3498db', textDecoration: 'none' }}>
                {label}
              </Link>
            )}
          </span>
        );
      })}
    </nav>
  );
}

Redirects

Mit Navigate-Komponente

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

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      {/* Alte URL auf neue umleiten */}
      <Route path="/home" element={<Navigate to="/" replace />} />
      <Route path="/blog" element={<Navigate to="/articles" replace />} />
      <Route path="/articles" element={<Articles />} />
    </Routes>
  );
}

Bedingte Redirects

function Dashboard() {
  const { isLoggedIn } = useAuth();

  if (!isLoggedIn) {
    return <Navigate to="/login" replace />;
  }

  return (
    <div>
      <h1>Dashboard</h1>
      {/* Dashboard-Inhalt */}
    </div>
  );
}

useLocation Hook

Zugriff auf die aktuelle URL und deren Details:

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

function CurrentPage() {
  const location = useLocation();

  return (
    <div>
      <p>Pfad: {location.pathname}</p>
      <p>Query: {location.search}</p>
      <p>Hash: {location.hash}</p>
    </div>
  );
}
// URL: /products?sort=price#top
// Pfad: /products
// Query: ?sort=price
// Hash: #top

Seiten-Tracking

function PageTracker() {
  const location = useLocation();

  useEffect(() => {
    // Analytics tracken
    console.log('Seite aufgerufen:', location.pathname);
    // analytics.trackPageView(location.pathname);
  }, [location]);

  return null; // Rendert nichts
}

// In App.jsx einbinden
function App() {
  return (
    <BrowserRouter>
      <PageTracker />
      <Routes>{/* ... */}</Routes>
    </BrowserRouter>
  );
}

Scroll-to-Top

React Router scrollt standardmaessig nicht nach oben bei Navigation:

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

// In App.jsx
function App() {
  return (
    <BrowserRouter>
      <ScrollToTop />
      <Routes>{/* ... */}</Routes>
    </BrowserRouter>
  );
}

State beim Navigieren uebergeben

Du kannst beim Navigieren State mitgeben, der nicht in der URL sichtbar ist:

import { Link, useLocation } from 'react-router-dom';

// State senden
function ProductList() {
  return (
    <Link
      to="/products/42"
      state={{ fromPage: 'product-list', searchQuery: 'laptop' }}
    >
      Produkt ansehen
    </Link>
  );
}

// State empfangen
function ProductDetail() {
  const location = useLocation();
  const { fromPage, searchQuery } = location.state || {};

  return (
    <div>
      {fromPage && (
        <Link to={`/products?q=${searchQuery}`}>
          Zurueck zur Liste
        </Link>
      )}
      <h1>Produktdetail</h1>
    </div>
  );
}

Mit useNavigate

const navigate = useNavigate();

navigate('/checkout', {
  state: { cartItems: items, total: 99.99 }
});

Praktisches Beispiel: Komplette Navigation

import { NavLink, Outlet, useLocation } from 'react-router-dom';

function AppLayout() {
  const location = useLocation();
  const pageTitle = {
    '/': 'Startseite',
    '/products': 'Produkte',
    '/about': 'Ueber uns',
    '/contact': 'Kontakt'
  };

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      {/* Header mit Navigation */}
      <header style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: '1rem 2rem',
        backgroundColor: '#fff',
        boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
        position: 'sticky',
        top: 0,
        zIndex: 100
      }}>
        <NavLink to="/" style={{ fontSize: '1.5rem', fontWeight: 'bold', textDecoration: 'none', color: '#3498db' }}>
          MeineApp
        </NavLink>
        <nav style={{ display: 'flex', gap: '1.5rem' }}>
          {[
            { to: '/', label: 'Home' },
            { to: '/products', label: 'Produkte' },
            { to: '/about', label: 'Ueber uns' },
            { to: '/contact', label: 'Kontakt' }
          ].map(link => (
            <NavLink
              key={link.to}
              to={link.to}
              end={link.to === '/'}
              style={({ isActive }) => ({
                textDecoration: 'none',
                color: isActive ? '#3498db' : '#555',
                fontWeight: isActive ? '600' : '400',
                borderBottom: isActive ? '2px solid #3498db' : '2px solid transparent',
                paddingBottom: '4px'
              })}
            >
              {link.label}
            </NavLink>
          ))}
        </nav>
      </header>

      {/* Hauptinhalt */}
      <main style={{ flex: 1, padding: '2rem', maxWidth: '1200px', margin: '0 auto', width: '100%' }}>
        <Outlet />
      </main>

      {/* Footer */}
      <footer style={{
        padding: '1.5rem 2rem',
        backgroundColor: '#2c3e50',
        color: '#ecf0f1',
        textAlign: 'center'
      }}>
        <p>2026 MeineApp. Alle Rechte vorbehalten.</p>
      </footer>
    </div>
  );
}

Uebungen

  1. Erstelle eine Navigation mit NavLink, die den aktiven Link visuell hervorhebt
  2. Baue eine Breadcrumb-Komponente, die den aktuellen Pfad anzeigt
  3. Implementiere ScrollToTop und teste es mit langen Seiten

Was kommt als Naechstes?

Du beherrschst jetzt Navigation in React. Im naechsten Kapitel lernst du geschuetzte Routen – wie du Seiten nur fuer eingeloggte Benutzer zugaenglich machst.

Zusammenfassung

  • NavLink bietet automatische Active-States fuer die Navigation
  • Die end-Prop verhindert, dass ”/” immer als aktiv markiert wird
  • Breadcrumbs helfen dem User bei der Orientierung
  • <Navigate> erstellt Redirects in JSX
  • useLocation gibt Zugriff auf die aktuelle URL
  • ScrollToTop behebt das fehlende Scroll-Verhalten bei Navigation
  • State kann bei Navigation unsichtbar mitgegeben werden

Pro-Tipp: Speichere deine Routen-Konfiguration in einer zentralen Datei (z.B. routes.js). So hast du einen Ueberblick ueber alle Seiten deiner App und kannst Navigation und Breadcrumbs einfacher generieren!

Zurück zum React Kurs