Setting Up Basic Routes in React

Introduction

As React applications grow, managing navigation between different views becomes essential. Instead of reloading the entire page, React allows single-page applications (SPAs) where components dynamically render based on the URL. This behavior is achieved through routing.

React Router is the most popular library for handling routing in React. It provides declarative tools to define routes and render components based on the current URL.

In this post, we will cover:

  • Creating multiple pages/components
  • Defining routes using Route and path
  • Rendering components dynamically based on URL
  • A practical example with Home, About, and Contact pages

Installing React Router

Before creating routes, install the React Router library:

npm install react-router-dom
  • react-router-dom is the package for browser-based routing.
  • Provides components like BrowserRouter, Routes, Route, and Link.

Creating Multiple Pages/Components

React routing relies on separate components representing different pages.

Example Components

// Home.js
import React from 'react';

function Home() {
  return <h1>Welcome to the Home Page</h1>;
}

export default Home;

// About.js
import React from 'react';

function About() {
  return <h1>About Us</h1>;
}

export default About;

// Contact.js
import React from 'react';

function Contact() {
  return <h1>Contact Page</h1>;
}

export default Contact;
  • Each component represents a distinct page in the app.
  • Components can include more complex JSX, forms, or API calls.

Defining Routes with Route and Path

React Router uses the Route component to associate a URL path with a component.

Basic Routing Setup

import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

function App() {
  return (
&lt;Router&gt;
  &lt;Routes&gt;
    &lt;Route path="/" element={&lt;Home /&gt;} /&gt;
    &lt;Route path="/about" element={&lt;About /&gt;} /&gt;
    &lt;Route path="/contact" element={&lt;Contact /&gt;} /&gt;
  &lt;/Routes&gt;
&lt;/Router&gt;
); } export default App;

Explanation:

  • BrowserRouter (aliased as Router) wraps the entire app to enable routing.
  • Routes contains all Route definitions.
  • Each Route has a path and an element to render.
  • Visiting /about renders the About component, /contact renders Contact.

Navigating Between Pages

To navigate without reloading the page, use the Link component instead of <a> tags.

Example Navigation

import React from 'react';
import { Link } from 'react-router-dom';

function Navbar() {
  return (
&lt;nav&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;Link to="/"&gt;Home&lt;/Link&gt;&lt;/li&gt;
    &lt;li&gt;&lt;Link to="/about"&gt;About&lt;/Link&gt;&lt;/li&gt;
    &lt;li&gt;&lt;Link to="/contact"&gt;Contact&lt;/Link&gt;&lt;/li&gt;
  &lt;/ul&gt;
&lt;/nav&gt;
); } export default Navbar;

Key Points:

  • to prop specifies the target route.
  • Clicking a link updates the URL and renders the corresponding component without reloading the page.

Nested Routes

React Router allows nested routes for layouts or sub-pages.

// Dashboard.js
import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';
import Profile from './Profile';
import Settings from './Settings';

function Dashboard() {
  return (
&lt;div&gt;
  &lt;h1&gt;Dashboard&lt;/h1&gt;
  &lt;nav&gt;
    &lt;Link to="profile"&gt;Profile&lt;/Link&gt;
    &lt;Link to="settings"&gt;Settings&lt;/Link&gt;
  &lt;/nav&gt;
  &lt;Routes&gt;
    &lt;Route path="profile" element={&lt;Profile /&gt;} /&gt;
    &lt;Route path="settings" element={&lt;Settings /&gt;} /&gt;
  &lt;/Routes&gt;
&lt;/div&gt;
); } export default Dashboard;
  • Nested routes allow sub-components under a parent path.
  • Visiting /dashboard/profile renders the Profile component inside Dashboard.

Dynamic Routes

Routes can be dynamic with parameters in the URL.

import React from 'react';
import { useParams } from 'react-router-dom';

function User() {
  const { id } = useParams();
  return <h2>User ID: {id}</h2>;
}

// Route definition
<Route path="/user/:id" element={<User />} />
  • :id is a route parameter.
  • useParams hook retrieves the parameter value.
  • Useful for detail pages, profiles, or dynamic content.

Handling 404 Pages

To display a fallback for undefined routes, use a wildcard path:

function NotFound() {
  return <h1>404 - Page Not Found</h1>;
}

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
  <Route path="/contact" element={<Contact />} />
  <Route path="*" element={<NotFound />} />
</Routes>
  • The * path matches all unmatched URLs.
  • Ensures users see a meaningful message for invalid routes.

Example: Home, About, Contact Pages

Complete App.js

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
import NotFound from './NotFound';

function App() {
  return (
&lt;Router&gt;
  &lt;header&gt;
    &lt;nav&gt;
      &lt;ul&gt;
        &lt;li&gt;&lt;Link to="/"&gt;Home&lt;/Link&gt;&lt;/li&gt;
        &lt;li&gt;&lt;Link to="/about"&gt;About&lt;/Link&gt;&lt;/li&gt;
        &lt;li&gt;&lt;Link to="/contact"&gt;Contact&lt;/Link&gt;&lt;/li&gt;
      &lt;/ul&gt;
    &lt;/nav&gt;
  &lt;/header&gt;
  &lt;main&gt;
    &lt;Routes&gt;
      &lt;Route path="/" element={&lt;Home /&gt;} /&gt;
      &lt;Route path="/about" element={&lt;About /&gt;} /&gt;
      &lt;Route path="/contact" element={&lt;Contact /&gt;} /&gt;
      &lt;Route path="*" element={&lt;NotFound /&gt;} /&gt;
    &lt;/Routes&gt;
  &lt;/main&gt;
&lt;/Router&gt;
); } export default App;
  • Combines routing, navigation, and fallback page.
  • Each page is a separate component.
  • Navigation links dynamically update the content.

Best Practices for Routing

  1. Keep routes declarative with Routes and Route.
  2. Use nested routes for layouts or sections.
  3. Use Link instead of <a> to prevent page reloads.
  4. Handle 404 pages for unknown routes.
  5. Use route parameters for dynamic content.
  6. Organize components by route or feature for clarity.
  7. Lazy load routes for performance optimization in large apps.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *