This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Implementing React Routing

  • ReactJS
  • November 15, 2024

Share On :

Introduction 

React is a popular JavaScript library for building single-page applications (SPAs), where the user navigates across different views without reloading the entire page. In SPAs, React efficiently updates the view based on user interactions, creating a smooth and dynamic user experience. However, React, by itself, doesn’t come with built-in routing functionality.

Prerequisites
  • Node.js and npm
  • React
  • Typescript
  • React Router DOM
Why do we need React Router DOM?

In traditional multi-page applications, each page change requires a full reload from the server. In a React app, we want the view to change while keeping users on the same page, enabling the SPA to dynamically render different components based on the URL. This is where React Router DOM comes in, a library specifically designed to handle client-side routing in React applications. It enables seamless navigation, URL updates, and view rendering without refreshing the page.

With React Router DOM, developers can define various routes within a React app and control which components appear for each URL path. This setup allows users to navigate between sections without experiencing the delays or reloads typical of traditional websites. Thus, React Router DOM is essential for managing navigation and ensuring a smooth user experience in modern, single-page applications.

Advantages of React Router DOM
  • Efficient Navigation : React Router DOM allows for seamless navigation within a single-page application without reloading the page, providing a smooth user experience.
  • Dynamic Routing : With React Router, routes can be configured and updated dynamically based on the app’s state or user actions, making it flexible for interactive applications.
  • Nested Routes : React Router DOM supports nested routing, allowing you to structure your app’s navigation in a hierarchical way. This is ideal for complex layouts with multiple levels of navigation.
  • Declarative Routing : React Router DOM lets you define routes declaratively within the JSX structure, making it more intuitive to manage and read in the component structure.
  • URL Synchronization : It keeps the URL in sync with the current view, enabling users to bookmark and share specific pages. The URL update also makes it easier for developers to manage state based on the route.
  • Built-in Hooks : React Router DOM provides hooks like useHistory, useLocation, and useParams for easy access to routing context, making it simpler to manage routes programmatically.
Disadvantages of React Router DOM
  • Client-Side Only : React Router DOM is primarily designed for client-side rendering, which can lead to SEO issues for certain applications because search engines may have trouble indexing client-rendered content. For server-rendered applications, you may need additional libraries like Next.js.
  • Initial Loading Overhead : In larger applications with complex routing, the initial load time can be slower, as the browser loads all components and routes required to manage a single-page app.
  • State Management Complexity : As routes become more dynamic and nested, managing and syncing state across components and routes can become complex, especially in larger applications.
  • Learning Curve : React Router DOM can introduce additional concepts (such as nested routes, dynamic parameters, and programmatic navigation) that may take time to understand, especially for beginners in React.
  • Memory and Performance : With complex nested routes, memory usage can increase as each route may need to hold onto its component state. If not managed correctly, this can lead to performance issues.
Common Pitfalls and Challenges in React Router DOM
  • Route Mismatches : Route ordering is essential in React Router, especially when using dynamic or nested routes. A more general route, if placed before a specific one, may lead to unexpected behavior or display incorrect components.
  • Incorrect URL Parameters : Mismanagement of URL parameters can lead to inconsistent app behavior. For example, a missing or incorrect parameter in the URL can cause certain components to break or not render as expected.
  • Component State Reset on Route Change : Sometimes, changing routes may cause components to reset their internal state, leading to a loss of user input or other critical state data. Proper state management or using libraries like Redux can help alleviate this.
  • Deeply Nested Routes Complexity : Complex nested routes can lead to hard-to-read code and navigation bugs. Managing deeply nested layouts requires thoughtful planning of route structure and may benefit from modularizing route components.
  • SEO Limitations : Since React Router DOM handles client-side routing, the lack of server-rendering support can impact SEO for certain apps. While this isn’t always a problem, apps that need search engine indexing may require additional configuration, or even frameworks that handle server-side rendering.
Mastering Routing with React Router DOM: A Demo App

As React Router DOM offers a plethora of features for handling navigation in React applications, we’ll focus on some key functionalities in this demo app. This app is designed to showcase how React Router DOM can streamline routing in a React with TypeScript environment. The News Application features multiple pages such as Home, World, Sports, Entertainment, and Technology, demonstrating how to manage routing efficiently.

In this demo, we’ll cover how to:

  • Set up basic routing for multiple pages.
  • Handle route transitions and navigation.
  • Implement error handling for undefined routes.

This example highlights how React Router DOM can simplify navigation across your application, keeping the structure clean and maintainable. By following along with this demo, you’ll learn how to implement React Router DOM in your own React TypeScript projects.

Folder Structure

src/

├── assets/

│   └── images/

│       ├── entertainment/

│       │   └── entertainment.png

│       ├── error/

│       │   └── error.png

│       ├── home/

│       │   ├── entertainment.png

│       │   ├── global.png

│       │   ├── sports.png

│       │   └── technology.png

│       ├── sports/

│       │   └── techInSports.png

│       ├── technology/

│       │   └── virtualReality.png

│       ├── world/

│       │   └── world.png

├── components/

│   ├── Layout.tsx

│   └── Navbar.tsx

├── pages/

│   ├── Home/

│   │   └── Home.tsx

│   ├── World/

│   │   └── World.tsx

│   ├── Sports/

│   │   └── Sports.tsx

│   ├── Entertainment/

│   │   └── Entertainment.tsx

│   └── Technology/

│       └── Technology.tsx

└── App.tsx

Navigating the Frontend Setup in React with React Router DOM

We’ll begin by structuring the app to include multiple pages such as Home, World, Sports, Entertainment, and Technology, and integrate smooth navigation between them. We will also highlight how to set up route handling, manage transitions, and gracefully handle errors with error boundaries.

Initializing the React Application

To get started, create a new React project with TypeScript if you haven’t already. You can set it up using the following command:

				
					//Create react app using the following command
npx create-react-app news-websites --template typescript

//Install the required library
npm install react-router-dom
npm install @types/react-router-dom


				
			

Steps to Set Up Routing in the React Application

To implement routing in the app, follow the steps below. This will guide you through organizing your components, pages, and assets in a way that makes routing seamless and intuitive.

  1. Create a components Folder
    Inside the src directory, create a folder named components. This folder will contain the components that are used throughout your app, such as the layout and navigation components.
    • Layout.tsx : This component will serve as the wrapper for the pages, including the Navbar and the Outlet where the page content will be displayed.
    • Navbar.tsx : The navigation bar component that contains the links for the different pages like Home, World, Sports, Entertainment, and Technology.
  2. Create a pages Folder
    Create a folder named pages inside the src directory. Each folder in this directory will represent a page in the app.
    • Home : This folder will contain the Home.tsx component, representing the homepage of the app.
    • World : Contains the World.tsx component.
    • Sports : Contains the Sports.tsx component.
    • Entertainment :  Contains the Entertainment.tsx component.
    • Technology : Contains the Technology.tsx component.
  3. Create an assets Folder
    Inside the src directory, create an assets folder to store your images. The assets/images/ subdirectory should be organized by category. You already have the following structure:
    • entertainment : Stores images for the entertainment section.
    • error : Stores error images for the app.
    • home : Contains images used on the home page.
    • sports : Contains images related to sports.
    • technology : Contains images related to technology.
    • world : Contains images for the world section.
  4. Create the App.tsx File
    The App.tsx file is the main entry point for the app. It is responsible for setting up routes using react-router-dom and rendering the appropriate components based on the URL.
				
					
//App.tsx

//Necessary Imports

const router = createBrowserRouter([
  {
    path: "/",
    element: <Layout />,
    errorElement: <ErrorPage />, 
    children: [
      { index: true, element: <Home /> },
      { path: "world", element: <World /> },
      { path: "sports", element: <Sports /> },
      { path: "entertainment", element: <Entertainment /> },
      { path: "technology", element: <Technology /> },
    ],
  },
]);

function App() {
  return <RouterProvider router={router} />;
}

export default App;


				
			
Routing Setup
  • The code uses createBrowserRouter from react-router-dom to configure the app’s routing.
Layout Component
  • The base route (/) is mapped to the Layout component, which serves as a wrapper for all child pages.
Child Routes
  • The child routes (e.g., Home, World, Sports, Entertainment, Technology) are nested under the base route, and each renders its corresponding component.
Error Handling
  • If an invalid route is accessed, the ErrorPage component is displayed using the errorElement property.
RouterProvider
  • The RouterProvider component is used to apply the defined router configuration to the App component.
Path Usage
  • The paths used in the router configuration are relative paths.
  • For example, in the child routes like { path: “world”, element: <World /> }, the path “world” is relative to the base route (/), meaning it will resolve to /world.
  • The path: “/” for the Layout component is the base route, and other routes like /sports, /entertainment, etc., are resolved relative to this base.
  • This configuration uses relative paths, meaning they are treated as paths within the context of the base route (/). If an absolute path were used (e.g., /sports), it would be a fixed path starting from the root of the URL.
				
					
//Layout.tsx

//Necessary Imports

const Layout: React.FC = () => {
  const navigation = useNavigation();

  return (
    <div
    >
      <Navbar />
      <Container>
        <Box my={4}>
          {navigation.state === "loading" && <p>Loading...</p>}
          <Outlet />
        </Box>
      </Container>
    </div>
  );
};

export default Layout;


				
			
  • Navbar : The Navbar component is rendered at the top of the page for navigation.
  • Outlet : The Outlet component renders the matched child route’s component within the Layout, acting as a placeholder for the content of the active route.
  • Loading State : The component uses useNavigation from react-router-dom to check the navigation state. If the navigation is in the loading state (navigation.state === “loading”), it displays a “Loading…” message.
				
					
//Navbar.tsx

//Necessary Imports

const Navbar: React.FC = () => {
  return (
    <AppBar position="sticky" sx={{ backgroundColor: "#333" }}>
      <Toolbar>
        <Typography variant="h6" sx={{ flexGrow: 1 }}>
          News Website
        </Typography>
        <Box sx={{ display: "flex", gap: 3 }}>
          <NavLink
            to="/"
            style={({ isActive }) => ({
              textDecoration: "none",
              fontWeight: isActive ? "bold" : "normal",
              color: isActive ? "#EFCC00" : "white",
            })}
          >
            Home
          </NavLink>
          <NavLink
            to="/world"
            style={({ isActive }) => ({
              textDecoration: "none",
              fontWeight: isActive ? "bold" : "normal",
              color: isActive ? "#EFCC00" : "white",
            })}
          >
            World
          </NavLink>
          <NavLink
            to="/entertainment"
            style={({ isActive }) => ({
              textDecoration: "none",
              fontWeight: isActive ? "bold" : "normal",
              color: isActive ? "#EFCC00" : "white",
            })}
          >
            Entertainment
          </NavLink>
          <NavLink
            to="/technology"
            style={({ isActive }) => ({
              textDecoration: "none",
              fontWeight: isActive ? "bold" : "normal",
              color: isActive ? "#EFCC00" : "white",
            })}
          >
            Technology
          </NavLink>
          <NavLink
            to="/sports"
            style={({ isActive }) => ({
              textDecoration: "none",
              fontWeight: isActive ? "bold" : "normal",
              color: isActive ? "#EFCC00" : "white",
            })}
          >
            Sports
          </NavLink>
        </Box>
      </Toolbar>
    </AppBar>
  );
};

export default Navbar;


				
			
  • Displays Navigation Links : The component renders a series of navigation links (Home, World, Entertainment, Technology, Sports) using the NavLink component from react-router-dom.
  • What is NavLink?
    NavLink is a special type of link provided by react-router-dom used for navigation within React applications. Unlike a standard anchor (<a>) tag, NavLink automatically manages navigation and styling based on the active route.
  • Navigation : Each NavLink is associated with a specific route (to=”/”, to=”/world”, etc.). When clicked, NavLink updates the URL and renders the corresponding component for that route.
  • Active Link Styling : NavLink automatically applies special styles when the route it links to is active. This is achieved using the isActive property, which allows you to customize the appearance of the active link (e.g., making it bold or changing its color).
				
					
//Home.tsx

//Necessary Imports

const Home: React.FC = () => {
  return (
    <Box>
      <Container >
        <Typography variant="h3">
          {Content}
        </Typography>
        <Typography variant="body1">
          {Content}
        </Typography>

        <Typography variant="h4">
           {Content}
        </Typography>

        <Grid container spacing={4}>
          <Grid item xs={12} md={6}>
            <Box>
              <img
                src={Global}
                alt="Breaking News"
              />
              <Typography variant="h5">
                {Content}
              </Typography>
              <Typography variant="body1">
               {Content}
              </Typography>
            </Box>
          </Grid>

          <Grid item xs={12} md={6}>
            <Box>
              <img
                src={Entertainment}
                alt="Entertainment"
              />
              <Typography variant="h5">
                {Content}
              </Typography>
              <Typography variant="body1">
               {Content}
              </Typography>
            </Box>
          </Grid>

          <Grid item xs={12} md={6}>
            <Box>
              <img
                src={Technology}
                alt="Technology"
              />
              <Typography variant="h5">
                {Content}
              </Typography>
              <Typography variant="body1">
               {Content}
              </Typography>
            </Box>
          </Grid>

          <Grid item xs={12} md={6}>
            <Box>
              <img
                src={Sports}
                alt="Sports"
              />
              <Typography variant="h5">
               {Content}
              </Typography>
              <Typography variant="body1">
                {Content}
              </Typography>
            </Box>
          </Grid>
        </Grid>
      </Container>
    </Box>
  );
};

export default Home;


				
			
  • The Home component is the landing page of the website. It displays the welcome message, a brief description of the website, and a section for the latest headlines across various categories like global news, entertainment, sports, and technology. 
  • Similar structure and functionality are followed in other pages as well.
Output
homePage
world | Implementing React Routing
entertainmentPage | Implementing React Routing
technologyPage scaled | Implementing React Routing
sportsPage | Implementing React Routing
errorPage | Implementing React Routing
Conclusion

In conclusion, this app demonstrates an organized and user-friendly layout for a news website, with smooth navigation across pages using react-router-dom. Each section—Home, World, Entertainment, Sports, and Technology—provides a dedicated space for content, and the use of React Router DOM enables efficient, SPA-style navigation without full-page reloads. This setup ensures that users have a seamless browsing experience, and the structure makes it easy to add or update sections as needed. Overall, the app highlights React’s capability to build scalable, navigable, and dynamic web applications.

Explore Our Services

Stay informed about our ReactJS Development services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

March 27, 2024
Authentication and Authorization in React
July 19, 2024
Simplifying State with Context API
Simplifying State with Context API
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform User-Friendly, Secure and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 4, 2023
Telemedicine Appointment & Health Record Portal
Telemedicine Appointment & Health Record Portal

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram