React Router — مقدمة React
React Router
React Router هي المكتبة الأكثر استخداماً للتنقل في تطبيقات React.
التثبيت
npm install react-router-domالإعداد الأساسي
import {
BrowserRouter,
Routes,
Route,
Link,
NavLink
} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">الرئيسية</Link>
<Link to="/about">من نحن</Link>
<Link to="/contact">اتصل بنا</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}Dynamic Routes
import { Routes, Route, useParams, useSearchParams } from 'react-router-dom';
// المسارات (داخل <Routes>)
const routes = (
<Routes>
<Route path="/users/:userId" element={<UserProfile />} />
<Route path="/products/:category/:id" element={<Product />} />
</Routes>
);
// Component
function UserProfile() {
const { userId } = useParams();
return <h1>المستخدم: {userId}</h1>;
}
function Product() {
const { category, id } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
const sort = searchParams.get('sort') || 'newest';
return (
<div>
<h1>منتج {id} من قسم {category}</h1>
<p>الترتيب: {sort}</p>
<button onClick={() => setSearchParams({ sort: 'price' })}>
ترتيب بالسعر
</button>
</div>
);
}Navigation البرمجي
import { useNavigate, useLocation } from 'react-router-dom';
function LoginForm() {
const navigate = useNavigate();
const location = useLocation();
const handleSubmit = async (e) => {
e.preventDefault();
// تسجيل الدخول
await login(credentials);
// العودة للصفحة السابقة أو الرئيسية
const from = location.state?.from || '/';
navigate(from, { replace: true });
};
return (
<form onSubmit={handleSubmit}>
{/* ... */}
<button type="submit">تسجيل الدخول</button>
</form>
);
}
// التنقل
navigate('/dashboard'); // الذهاب
navigate(-1); // رجوع
navigate('/login', { replace: true }); // استبدال
navigate('/profile', { state: { from: location } });Nested Routes
import { Routes, Route, Link, Outlet } from 'react-router-dom';
// Layout مع Outlet
function Dashboard() {
return (
<div className="dashboard">
<Sidebar />
<main>
<Outlet /> {/* هنا تظهر الصفحات الفرعية */}
</main>
</div>
);
}
// المسارات المتداخلة
const routes = (
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route index element={<DashboardHome />} />
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
);
// الروابط
function DashboardNav() {
return (
<nav>
<Link to="/dashboard">الرئيسية</Link>
<Link to="/dashboard/profile">الملف الشخصي</Link>
<Link to="/dashboard/settings">الإعدادات</Link>
</nav>
);
}Protected Routes
import { Navigate, useLocation } from 'react-router-dom';
function ProtectedRoute({ children }) {
const { isLoggedIn } = useAuth();
const location = useLocation();
if (!isLoggedIn) {
// حفظ الموقع الحالي للعودة بعد تسجيل الدخول
return (
<Navigate
to="/login"
state={{ from: location.pathname }}
replace
/>
);
}
return children;
}
// استخدام
<Route
path="/dashboard/*"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>NavLink للتنسيق
<NavLink
to="/about"
className={({ isActive }) =>
isActive ? "nav-link active" : "nav-link"
}
style={({ isActive }) => ({
fontWeight: isActive ? "bold" : "normal"
})}
>
من نحن
</NavLink>Lazy Loading
import { lazy, Suspense } from 'react';
// تحميل كسول
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Profile = lazy(() => import('./pages/Profile'));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}import {
BrowserRouter,
Routes,
Route,
Link,
useParams,
useNavigate
} from 'react-router-dom';
// الصفحات
function Home() {
return <h1>الصفحة الرئيسية</h1>;
}
function Products() {
const products = [
{ id: 1, name: 'منتج 1' },
{ id: 2, name: 'منتج 2' },
];
return (
<div>
<h1>المنتجات</h1>
<ul>
{products.map(p => (
<li key={p.id}>
<Link to={`/products/${p.id}`}>{p.name}</Link>
</li>
))}
</ul>
</div>
);
}
function ProductDetail() {
const { id } = useParams();
const navigate = useNavigate();
return (
<div>
<h1>تفاصيل المنتج {id}</h1>
<button onClick={() => navigate(-1)}>رجوع</button>
</div>
);
}
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">الرئيسية</Link>
<Link to="/products">المنتجات</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:id" element={<ProductDetail />} />
</Routes>
</BrowserRouter>
);
}اختبر فهمك