App in ONE router at the root level. Never nest routers.// --- App.js (Parent) ---
import React from 'react';
function App() {
return <div className="App"><h1>React Router</h1></div>;
}
export default App;
// --- main.jsx (Entry Point) ---
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
// Choose ONE router type for your app:
// 1. BrowserRouter (Standard, uses HTML5 history API)
// 2. HashRouter (Uses URL hash, good for static hosting)
// 3. MemoryRouter (Keeps history in memory, good for testing)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
<Link> for basic navigation. Use <NavLink> when you need to style the active route.// --- App.js (Parent) ---
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Navbar from './Navbar';
import Home from './Home';
import About from './About';
function App() {
return (
<div className="App">
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
);
}
export default App;
// --- Navbar.jsx (Child Component) ---
import React from 'react';
import { Link, NavLink } from 'react-router-dom';
const Navbar = () => {
return (
<nav className="navbar">
{/* Link: Basic navigation without active styling */}
<Link to="/">Home</Link>
{/* NavLink: Adds 'active' class when route matches */}
<NavLink
to="/about"
className={({ isActive }) =>
isActive ? 'nav-active' : 'nav-link'
}
>
About
</NavLink>
<Link to="/contact">Contact</Link>
</nav>
);
};
export default Navbar;
You were redirected here programmatically.
navigate('/path') after form submissions or API calls. Use {'{ replace: true }'} to prevent going back.// --- App.js (Parent) ---
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Login from './Login';
import Dashboard from './Dashboard';
function App() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
);
}
export default App;
// --- Login.jsx (Child Component) ---
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
const Login = () => {
const [username, setUsername] = useState('');
// Hook to programmatically change routes
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
if (username) {
// Navigate to dashboard, replacing history stack
navigate('/dashboard', { replace: true });
}
};
return (
<form onSubmit={handleSubmit}>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
<button type="submit">Login</button>
</form>
);
};
export default Login;
Fetching data for User ID: 42
<Route path="/user/:id" />, then read them with useParams().// --- App.js (Parent) ---
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import UserProfile from './UserProfile';
function App() {
return (
<Routes>
<Route path="/user/:id" element={<UserProfile />} />
</Routes>
);
}
export default App;
// --- UserProfile.jsx (Child Component) ---
import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
const UserProfile = () => {
// Hook to access dynamic URL segments (e.g., /user/:id)
const { id } = useParams();
return (
<div className="profile">
<p>User ID: {id}</p>
</div>
);
};
export default UserProfile;
Showing results for: react
// --- App.js (Parent) ---
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Search from './Search';
function App() {
return (
<Routes>
<Route path="/search" element={<Search />} />
</Routes>
);
}
export default App;
// --- Search.jsx (Child Component) ---
import React from 'react';
import { useSearchParams } from 'react-router-dom';
const Search = () => {
// Hook to read/write the URL query string (e.g., ?q=react)
const [searchParams, setSearchParams] = useSearchParams();
const q = searchParams.get('q') || '';
return (
<div>
<p>Results for: {q}</p>
</div>
);
};
export default Search;
useLocation in a <ScrollToTop> component to reset scroll position on route changes, or for analytics tracking.// --- App.js (Parent) ---
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import ScrollToTop from './ScrollToTop';
import Home from './Home';
function App() {
return (
<>
<ScrollToTop />
<Routes>
<Route path="/home" element={<Home />} />
</Routes>
</>
);
}
export default App;
// --- ScrollToTop.jsx (Child Component) ---
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
const ScrollToTop = () => {
// Hook to access the current location object
const { pathname } = useLocation();
useEffect(() => {
// Scroll to top whenever the pathname changes
window.scrollTo(0, 0);
}, [pathname]);
return null; // Renders nothing
};
export default ScrollToTop;
<Outlet /> in a parent layout component. React Router will render the matched child route in that spot.// --- App.js (Parent) ---
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Dashboard from './Dashboard';
import Overview from './Overview';
import Settings from './Settings';
function App() {
return (
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route index element={<Overview />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
);
}
export default App;
// --- Dashboard.jsx (Parent Layout) ---
import React from 'react';
import { Outlet, NavLink } from 'react-router-dom';
const Dashboard = () => {
return (
<div className="dashboard-layout">
<aside className="sidebar">
<h3>Dashboard</h3>
{/* Nested navigation */}
<NavLink to="overview">Overview</NavLink>
<NavLink to="settings">Settings</NavLink>
</aside>
<main className="content">
{/* Renders the matched child route component */}
<Outlet />
</main>
</div>
);
};
export default Dashboard;
You now know how to configure Routers, navigate declaratively and programmatically, read Params, and build Nested Layouts.
Next: State Management with Context & Redux
Global state management
Data flow & composition