Welcome back, coding friends! Today, we're diving into a fascinating topic: Pages and Routing in React JS. By the end of this tutorial, you'll be able to create multiple pages, navigate between them, and understand the power of routing in a React application. Let's get started! šÆ
In simple terms, a page is a separate view or screen in an application. Each page typically displays different content and can be navigated to and from other pages.
Routing, on the other hand, is the process of managing the navigation between these pages. It helps us to define the mapping between URLs and the corresponding pages to be displayed.
First, let's set up a new React project using Create React App:
npx create-react-app react-routing
cd react-routingTo create a new page in a React app, we'll create a new component, give it a unique name, and render it. Let's create a Home and About page for our example:
touch src/components/Home.js src/components/About.js// src/components/Home.js
import React from 'react';
const Home = () => {
return (
<div>
<h1>Welcome to our Home Page!</h1>
</div>
);
};
export default Home;// src/components/About.js
import React from 'react';
const About = () => {
return (
<div>
<h1>Learn about our amazing app here!</h1>
</div>
);
};
export default About;We'll use a popular routing library called react-router-dom to manage our pages and navigation. Install it using npm:
npm install react-router-domNow, let's import the necessary components and wrap our application with the BrowserRouter and Routes components:
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;Now, when you run the application and navigate to different URLs, the corresponding pages will be displayed!
What is the purpose of the `react-router-dom` library in this tutorial?
In the following sections, we'll learn about nested routes, dynamic routes, and protected routes. These concepts will help you create more complex and feature-rich applications.
Nested routes allow you to create a hierarchical structure of routes within other routes. This can be helpful for organizing content and improving navigation in larger applications.
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route, NavLink } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Services from './components/Services';
function App() {
return (
<Router>
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to="/services">Services</NavLink>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/services" element={<Services />}>
<Route path="subservice1" element={<SubService1 />} />
<Route path="subservice2" element={<SubService2 />} />
</Route>
</Routes>
</Router>
);
}
export default App;Dynamic routes allow you to create URLs that can change based on user input or other factors. This can be useful for creating pages with parameters or for creating generic pages that can display different content based on the URL.
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route, NavLink, useParams } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import ServiceDetails from './components/ServiceDetails';
function App() {
const { serviceId } = useParams();
return (
<Router>
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to={`/service/${serviceId}`}>Service Details</NavLink>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/service/:serviceId" element={<ServiceDetails serviceId={serviceId} />} />
</Routes>
</Router>
);
}
export default App;
// src/components/ServiceDetails.js
import React from 'react';
const ServiceDetails = ({ serviceId }) => {
return (
<div>
<h1>Service Details for service ID {serviceId}</h1>
</div>
);
};
export default ServiceDetails;Protected routes allow you to restrict access to certain pages based on user authentication or other conditions. This can be helpful for maintaining the security and integrity of your application.
// src/components/PrivateRoute.js
import React from 'react';
import { Outlet } from 'react-router-dom';
const PrivateRoute = ({ isAuthenticated, children, ...rest }) => {
return (
<Route
{...rest}
render={({ location }) =>
isAuthenticated ? (
children
) : (
<Navigate to="/login" replace state={{ from: location }} />
)
}
/>
);
};
export default PrivateRoute;
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route, NavLink, useParams } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import ServiceDetails from './components/ServiceDetails';
import PrivateRoute from './components/PrivateRoute';
import { useAuth } from './contexts/AuthContext';
function App() {
const { isAuthenticated } = useAuth();
return (
<Router>
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to="/service/:serviceId">Service Details</NavLink>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/service/:serviceId" element={<ServiceDetails />} />
<Route element={<PrivateRoute isAuthenticated={isAuthenticated} />}>
<Route path="/dashboard" element={<Dashboard />} />
</Route>
</Routes>
</Router>
);
}
export default App;That's it for today's tutorial on Pages and Routing in React JS! I hope you found it helpful and engaging. Stay tuned for more exciting tutorials at CodeYourCraft! š
š Note: In this tutorial, we used the useParams hook to access parameters from the URL and the useAuth hook to manage user authentication. These hooks are not part of the react-router-dom library but are part of the React context API.
š” Pro Tip: Be sure to check out the React Router documentation for more in-depth information and examples: React Router Documentation ā