React Router Tutorial | Navigation in React Apps
Introduction:
React Router
is mostly used library for managing the navigation in your applications. It
helps to build a single-page application with flexible and dynamic navigation.
This allows you to create a reusable component and manage state effectively.
Routers are used for creating multiple pages in your React application without
the re-rendering of full-page loads.
In this article, we will discuss the React Router tutorial and also Navigation in React Apps with practical examples.
Router in React:
This is a commonly used library for handling routing
in React applications. This provides a navigation to many components that don’t
need to refresh the whole page, managing a flexible and better user experience.
It can be easily updating the URL and renders the component without the need to
reload the browser.
Key Features of React Router:
Here are some of the key features of React Router
mentioned below:
1) Dynamic Routing:
This helps for including the dynamic arguments in
paths, allowing the creation the reusable routes that handle the data or input
user.
2) Nested Routes:
It provides a way of making the nested routes,
handling the hierarchical and complex UI structure. Parent routes are used for
managing the layouts, and Child routes are used for rendering the particular
content layouts.
3) Declarative Routing:
It allows you to declare the routes in the React
components such as <Route>, <Routes>, and <BrowserRouter>
because it uses the component-based approach.
4) Navigate the Components:
It gives the components such as <Link> and <NavLink> to make the navigation elements. With the use of
<Link>, you can easily generate the anchor tags, but <NavLink>
provides active links to define better feedback.
Set Up and Install the React Router:
Firstly, you can install the React Router in your
terminal.
npm install react-router-dom
After installation, set up like this
npx create-react-app my app
cd my app
npm start
Example
Code:
import React from 'react';
import { BrowserRouter as Router, Routes,
Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<div>
<header>
<h2>My Simple React Router Example</h2>
<nav>
<ul>
<li><Link
to="/">Dashboard</Link></li>
<li><Link
to="/services">Services</Link></li>
<li><Link
to="/profile">Profile</Link></li>
</ul>
</nav>
</header>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/services" element={<Services />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</div>
</Router>
);
}
function Dashboard() {
return <h3>Welcome to the Dashboard Page!</h3>;
}
function Services() {
return <h3>Here are our Services.</h3>;
}
function Profile() {
return <h3>This is your Profile Page.</h3>;
}
export default App;
Make the Navigation Links:
With the use of the Link component from the react-router-dom,
you can create the navigation links. It helps to render the component using an
anchor tag, but managing the routing doesn’t need a whole page refresh.
Example
Code:
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<ul style={{ listStyle: 'none', display: 'flex', gap: '15px' }}>
<li><Link to="/">Home</Link></li>
<li><Link
to="/about">About</Link></li>
<li><Link
to="/projects">Projects</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
);
}
export default Navbar;
Nested Routes in React Router:
It helps to manage the child components in a parent
route.
Example
Code:
import { Routes, Route, Link, Outlet }
from "react-router-dom";
function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
<nav>
<Link to="profile">Profile</Link> |{" "}
<Link to="settings">Settings</Link>
</nav>
<Outlet />
</div>
);
}
function Profile() {
return <h3>User Profile Page</h3>;
}
function Settings() {
return <h3>Settings Page</h3>;
}
function App() {
return (
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
);
}
export default App;
Programmatic Navigation:
Using the Redirect, you can perform the navigation to
navigate a particular route. Browser data are modified with the use of
useHistory().
Example
Code:
import { useNavigate } from
"react-router-dom";
function Signup() {
const navigate = useNavigate();
function handleSignup() {
alert("Signup successful!");
navigate("/welcome");
}
return (
<div>
<h2>Signup Page</h2>
<p>Please fill in your details to create an account.</p>
<button onClick={handleSignup}>Signup</button>
</div>
);
}
export default Signup;
Lazy Loading Routes:
It helps in managing the performance of optimization
with the use of lazy() and suspense() methods.
Example
Code:
import React, { lazy, Suspense } from
"react";
import { BrowserRouter, Routes, Route }
from "react-router-dom";
const Dashboard = lazy(() =>
import("./Dashboard"));
const Services = lazy(() =>
import("./Services"));
const Profile = lazy(() =>
import("./Profile"));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<h2>Loading page...</h2>}>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/services" element={<Services />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
export default App;
Protected Routes:
These routes are not allowed to access a page while
the user is not logged in.
Example
Code:
import React, { useState } from
"react";
import { BrowserRouter as Router, Routes,
Route, Navigate } from "react-router-dom";
const ProtectedRoute = ({ auth, children
}) => (auth ? children : <Navigate to="/login" />);
function App() {
const [auth, setAuth] = useState(false);
return (
<Router>
<Routes>
<Route path="/login" element={<button onClick={() =>
setAuth(true)}>Login</button>} />
<Route path="/dashboard" element={<ProtectedRoute
auth={auth}><h2>Dashboard</h2></ProtectedRoute>} />
</Routes>
</Router>
);
}
export default App;
Redirects in React Router:
If the user wants to perform the redirect from one
route to another, they can use the Navigate component.
Example
Code:
import React, { useState } from
"react";
import {
BrowserRouter as Router,
Routes,
Route,
Navigate,
Link,
useNavigate,
} from "react-router-dom";
function ProtectedRoute({ isAuthenticated,
children }) {
if
(!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return children;
}
function Home() {
return (
<div style={{ textAlign: "center", marginTop:
"50px" }}>
<h1>Welcome to Our Website</h1>
<p>This is a simple demo of protected routes using React
Router.</p>
<Link to="/dashboard">Go to
Dashboard</Link>
</div>
);
}
function Dashboard({ onLogout }) {
return (
<div style={{ textAlign: "center", marginTop:
"50px" }}>
<h2>Dashboard Page</h2>
<p>You can access this page only if you are logged in.</p>
<button onClick={onLogout}>Logout</button>
<br />
<br />
<Link to="/">Go to Home</Link>
</div>
);
}
function Login({ onLogin }) {
const navigate = useNavigate();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (username === "user" && password ===
"1234") {
onLogin();
navigate("/dashboard");
} else {
alert("Invalid credentials! Try user / 1234");
}
};
return (
<div style={{ textAlign: "center", marginTop:
"50px" }}>
<h2>Login Page</h2>
<form onSubmit={handleSubmit}>
<div>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
style={{ padding: "8px", margin: "5px" }}
/>
</div>
<div>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
style={{ padding: "8px", margin: "5px" }}
/>
</div>
<button type="submit" style={{ padding: "8px
16px" }}>
Login
</button>
</form>
<br />
<Link to="/">Go Back Home</Link>
</div>
);
}
function App() {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const handleLogin = () => setIsAuthenticated(true);
const handleLogout = () => setIsAuthenticated(false);
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login
onLogin={handleLogin} />} />
<Route
path="/dashboard"
element={
<ProtectedRoute isAuthenticated={isAuthenticated}>
<Dashboard
onLogout={handleLogout} />
</ProtectedRoute>
}
/>
<Route path="*" element={<h2>404 - Page Not
Found</h2>} />
</Routes>
</Router>
);
}
export default App;
Conclusion:
I hope this article gives you a deep understanding of React Router Tutorial from beginner to
professional-level developers. This is especially used in front-end
applications. It provides developers with flexible and reusable ways to manage
the dynamic routes, front-side navigation, and conditional rendering to improve
better user experience.
For a detailed and clear understanding of ReactJS, Tpoint
Tech website provides React tutorials, all related concepts, and other
programing tutorials in easy language.
Comments
Post a Comment