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.
- 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.
- 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.
- 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.
- 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: ,
errorElement: ,
children: [
{ index: true, element: },
{ path: "world", element: },
{ path: "sports", element: },
{ path: "entertainment", element: },
{ path: "technology", element: },
],
},
]);
function App() {
return ;
}
export default App;
- The code uses createBrowserRouter from react-router-dom to configure the app’s routing.
- The base route (/) is mapped to the Layout component, which serves as a wrapper for all child pages.
- The child routes (e.g., Home, World, Sports, Entertainment, Technology) are nested under the base route, and each renders its corresponding component.
- If an invalid route is accessed, the ErrorPage component is displayed using the errorElement property.
- The RouterProvider component is used to apply the defined router configuration to the App component.
- 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 (
{navigation.state === "loading" && Loading...
}
);
};
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 (
News Website
({
textDecoration: "none",
fontWeight: isActive ? "bold" : "normal",
color: isActive ? "#EFCC00" : "white",
})}
>
Home
({
textDecoration: "none",
fontWeight: isActive ? "bold" : "normal",
color: isActive ? "#EFCC00" : "white",
})}
>
World
({
textDecoration: "none",
fontWeight: isActive ? "bold" : "normal",
color: isActive ? "#EFCC00" : "white",
})}
>
Entertainment
({
textDecoration: "none",
fontWeight: isActive ? "bold" : "normal",
color: isActive ? "#EFCC00" : "white",
})}
>
Technology
({
textDecoration: "none",
fontWeight: isActive ? "bold" : "normal",
color: isActive ? "#EFCC00" : "white",
})}
>
Sports
);
};
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 (
{Content}
{Content}
{Content}
{Content}
{Content}
{Content}
{Content}
{Content}
{Content}
{Content}
{Content}
);
};
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
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.