Getting Started with React Router: A Beginner's Guide
Md Yusuf
Posted on September 30, 2024
React Router is a library for managing navigation in React applications. It enables you to create dynamic and single-page applications (SPAs) with routes. Here are the basics of React Router:
1. Installation
First, install the react-router-dom
package:
npm install react-router-dom
2. Setting Up Routes
To create routes, wrap your components with BrowserRouter
and use Routes
and Route
to define paths.
Example:
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;
3. Linking Between Routes
Use the Link
component to navigate between pages without refreshing.
Example:
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}
4. Route Parameters
You can create dynamic routes using parameters.
Example:
<Route path="/user/:id" element={<User />} />
// Access the parameter inside the component:
import { useParams } from 'react-router-dom';
function User() {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
}
5. Redirecting
To programmatically navigate, use useNavigate()
.
Example:
import { useNavigate } from 'react-router-dom';
function Login() {
const navigate = useNavigate();
const handleLogin = () => {
// Perform login logic
navigate('/dashboard');
};
return <button onClick={handleLogin}>Login</button>;
}
These are the key basics to start working with React Router!
💖 💪 🙅 🚩
Md Yusuf
Posted on September 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.