React Router Explanation:
React Router is a library that lets you create navigation and routes in a React app — like moving between pages without reloading the whole website.
React Router helps your React app behave like a multi-page website, even though it's actually a single-page application (SPA).
Basic Setup (React Router v6+)
- Install it:
npm install react-router-dom
- Set up routing in your app:
// App.js
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
Navigating with Link
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
);
}
This avoids full page reloads — it's all handled inside React.
Example Folder Structure:
src/
├── App.js
├── Home.js
├── About.js
Home.js
function Home() {
return <h1>Welcome to the Home Page</h1>;
}
export default Home;
About.js
function About() {
return <h1>About Us</h1>;
}
export default About;
Summary
Feature | Purpose |
---|---|
BrowserRouter |
Wraps your whole app |
Routes |
Groups all your <Route> s |
Route |
Defines a path and component |
Link |
Navigation without refresh |
useNavigate |
Programmatic navigation |
Top comments (0)