Implementing React Routing

Introduction to React Router DOM:
React helps you build single-page apps (SPAs), where users can switch between pages without reloading the whole page. It updates the content based on what the user does, which makes the app feel smooth. But React doesn’t have built-in routing, so developers use tools like React Router to handle navigation between pages.
Prerequisites:
- Node.js and npm
- React
- Typescript
- React Router DOM
Reference From: https://blog.logrocket.com/react-router-dom-tutorial-examples/
Why do we need React Router DOM?
React lets you create single-page apps (SPAs), where users can switch between pages without reloading the entire page. It updates content based on user actions, making the app smooth. However, React doesn’t have built-in routing, so developers use tools like React Router to manage navigation.
React Router DOM improves the user experience, particularly for single-page apps. It lets users switch between different sections without the delays or reloading that typically happen on traditional websites. It's a key tool that helps make navigation smooth in modern web apps.
Advantages of React Router DOM:
- Efficient Navigation: React Router DOM lets users move around the app without reloading the page, providing a smooth experience.
- Dynamic Routing: React Router easily updates routes based on the app’s state or what the user does.
- 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 get more dynamic and nested, keeping track of state across components and routes can get complicated, especially in larger apps.
- Learning Curve: Learning React Router DOM can be tricky at first. You’ll come across concepts like nested routes, dynamic parameters, and programmatic navigation, which can be hard to understand, especially for beginners.
- Memory and Performance: Also, with complex nested routes, memory use can go up. Each route might need to store its own component state, which could slow things down if not managed properly.
Common Pitfalls and Challenges in React Router DOM:
- Route Order: Make sure to place specific routes before general ones. If you put a general route first, it might show the wrong component or not match the right route.
- Incorrect URL Parameters: If URL parameters aren’t handled properly, it can lead to problems. For example, missing or incorrect parameters can cause certain components to break or not display properly.
- Component State Reset on Route Change: Changing routes can sometimes reset a component’s internal state, which can result in losing user input or other important data. Using proper state management or tools like Redux can prevent issues like losing state during route changes.
- Deeply Nested Routes Complexity: Too many nested routes can clutter the code and cause navigation problems. Careful planning and breaking up route components can make this easier to manage.
- 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
This demo app shows how React Router DOM works with React and TypeScript. It has pages like Home, World, Sports, Entertainment, and Technology to demonstrate how routing lets you switch between pages.
In this demo, you’ll learn how to:
- Set up routing for different pages.
- Manage navigation and route changes.
- Handle errors for unknown routes.
This example demonstrates how React Router DOM makes navigation simple and keeps the app clean. By following along, you’ll see how to use React Router DOM in your own React TypeScript projects.
Folder Structure:
1src/
2├── assets/
3│ └── images/
4│ ├── entertainment/
5│ │ └── entertainment.png
6│ ├── error/
7│ │ └── error.png
8│ ├── home/
9│ │ ├── entertainment.png
10│ │ ├── global.png
11│ │ ├── sports.png
12│ │ └── technology.png
13│ ├── sports/
14│ │ └── techInSports.png
15│ ├── technology/
16│ │ └── virtualReality.png
17│ ├── world/
18│ │ └── world.png
19├── components/
20│ ├── Layout.tsx
21│ └── Navbar.tsx
22├── pages/
23│ ├── Home/
24│ │ └── Home.tsx
25│ ├── World/
26│ │ └── World.tsx
27│ ├── Sports/
28│ │ └── Sports.tsx
29│ ├── Entertainment/
30│ │ └── Entertainment.tsx
31│ └── Technology/
32│ └── Technology.tsx
33└── App.tsxNavigating the Frontend Setup in React with React Router DOM
We're building an app with pages like Home, World, Sports, Entertainment, and Technology. The app will let users easily switch between these pages. Along the way, we'll learn how to set up routes, add transitions, and handle errors with error boundaries.
Start the React App
If you don’t have a React project yet, you can make one like this:
1//Create react app using the following command
2npx create-react-app news-websites --template typescript
3
4//Install the required library
5npm install react-router-dom
6npm install @types/react-router-domSteps to Set Up Routing in the React Application
First, organize the app by setting up different folders and components. This will help in making routing work smoothly.
- Create a components Folder
- Inside the src folder, make a new folder called components. This is where you’ll store components like the layout and navbar.
- Layout.tsx: This will be the wrapper for the pages. It will include the Navbar and the area where the page content will go.
- Navbar.tsx: The navbar that will hold links to pages like Home, World, Sports, Entertainment, and Technology.
- Inside the src folder, make a new folder called components. This is where you’ll store components like the layout and navbar.
- Create a pages Folder
- Next, make another folder called pages inside the src folder. Each page will have its own folder here.
- 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: Images related to entertainment.
- error: Images related to errors.
- home: Images related to homepage here.
- sports: Images related to sports.
- technology: Images related to technology section.
- world: Images related to the world section here.
- 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:
- 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.
1//App.tsx
2
3//Necessary Imports
4
5const router = createBrowserRouter([
6 {
7 path: "/",
8 element: <Layout />,
9 errorElement: <ErrorPage />,
10 children: [
11 { index: true, element: <Home /> },
12 { path: "world", element: <World /> },
13 { path: "sports", element: <Sports /> },
14 { path: "entertainment", element: <Entertainment /> },
15 { path: "technology", element: <Technology /> },
16 ],
17 },
18]);
19
20function App() {
21 return <RouterProvider router={router} />;
22}
23
24export default App;Routing Setup:
- Here the code uses createBrowserRouter from react-router-dom to set up the app’s routing.
Layout Component:
- The main route (/) is connected to the Layout component, which wraps all the pages.
Child Routes:
- The child routes, such as Home, World, Sports, Entertainment, and Technology, are placed under the main route. Each of these will display its own page.
Error Handling:
- If the route is not valid, the Error Page component will be shown,due to the errorElement property.
RouterProvider:
- The RouterProvider is used to set up the routes for the App component.
Path Usage:
- The paths in the router are relative.
- For example, if we have { path: "world", element: <World /> }, "world" is relative to the main route (/), so it becomes /world.
- The Layout component uses the / path as the base route. Other routes like /sports or /entertainment are also based on this main route.
- In short, the paths are linked to the base route (/). If we used an absolute path, like /sports, it would go from the very start of the URL.
1//Layout.tsx
2
3//Necessary Imports
4
5const Layout: React.FC = () => {
6 const navigation = useNavigation();
7
8 return (
9 <div
10 >
11 <Navbar />
12 <Container>
13 <Box my={4}>
14 {navigation.state === "loading" && <p>Loading...</p>}
15 <Outlet />
16 </Box>
17 </Container>
18 </div>
19 );
20};
21
22export default Layout;- Navbar: The Navbar component appears at the top of the page to help users navigate.
- Outlet: The Outlet component displays the content of the active route within the Layout, serving as a placeholder for the matched route's component.
- Loading State: The component uses useNavigation from react-router-dom to check the navigation status. If the state is loading, it shows a loader message.
1//Navbar.tsx
2
3//Necessary Imports
4
5const Navbar: React.FC = () => {
6 return (
7 <AppBar position="sticky" sx={{ backgroundColor: "#333" }}>
8 <Toolbar>
9 <Typography variant="h6" sx={{ flexGrow: 1 }}>
10 News Website
11 </Typography>
12 <Box sx={{ display: "flex", gap: 3 }}>
13 <NavLink
14 to="/"
15 style={({ isActive }) => ({
16 textDecoration: "none",
17 fontWeight: isActive ? "bold" : "normal",
18 color: isActive ? "#EFCC00" : "white",
19 })}
20 >
21 Home
22 </NavLink>
23 <NavLink
24 to="/world"
25 style={({ isActive }) => ({
26 textDecoration: "none",
27 fontWeight: isActive ? "bold" : "normal",
28 color: isActive ? "#EFCC00" : "white",
29 })}
30 >
31 World
32 </NavLink>
33 <NavLink
34 to="/entertainment"
35 style={({ isActive }) => ({
36 textDecoration: "none",
37 fontWeight: isActive ? "bold" : "normal",
38 color: isActive ? "#EFCC00" : "white",
39 })}
40 >
41 Entertainment
42 </NavLink>
43 <NavLink
44 to="/technology"
45 style={({ isActive }) => ({
46 textDecoration: "none",
47 fontWeight: isActive ? "bold" : "normal",
48 color: isActive ? "#EFCC00" : "white",
49 })}
50 >
51 Technology
52 </NavLink>
53 <NavLink
54 to="/sports"
55 style={({ isActive }) => ({
56 textDecoration: "none",
57 fontWeight: isActive ? "bold" : "normal",
58 color: isActive ? "#EFCC00" : "white",
59 })}
60 >
61 Sports
62 </NavLink>
63 </Box>
64 </Toolbar>
65 </AppBar>
66 );
67};
68
69export default Navbar;- Shows Links: The NavBar displays links such as Home, World, Entertainment, Technology, and Sports, using NavLink from react-router-dom.
- What is NavLink?NavLink is a special kind of link in React. It’s different from a regular <a> tag because it makes navigation easier and highlights the active link.
- Navigation: Each NavLink points to a different route, such as to="/" or to="/world". When clicked, it changes the URL and shows the matching page.
- Active Link Styling: When a route is active, NavLink applies special styles to the link. You can change the appearance of the active link, like making it bold or changing its color.
1//Home.tsx
2
3//Necessary Imports
4
5const Home: React.FC = () => {
6 return (
7 <Box>
8 <Container >
9 <Typography variant="h3">
10 {Content}
11 </Typography>
12 <Typography variant="body1">
13 {Content}
14 </Typography>
15
16 <Typography variant="h4">
17 {Content}
18 </Typography>
19
20 <Grid container spacing={4}>
21 <Grid item xs={12} md={6}>
22 <Box>
23 <img
24 src={Global}
25 alt="Breaking News"
26 />
27 <Typography variant="h5">
28 {Content}
29 </Typography>
30 <Typography variant="body1">
31 {Content}
32 </Typography>
33 </Box>
34 </Grid>
35
36 <Grid item xs={12} md={6}>
37 <Box>
38 <img
39 src={Entertainment}
40 alt="Entertainment"
41 />
42 <Typography variant="h5">
43 {Content}
44 </Typography>
45 <Typography variant="body1">
46 {Content}
47 </Typography>
48 </Box>
49 </Grid>
50
51 <Grid item xs={12} md={6}>
52 <Box>
53 <img
54 src={Technology}
55 alt="Technology"
56 />
57 <Typography variant="h5">
58 {Content}
59 </Typography>
60 <Typography variant="body1">
61 {Content}
62 </Typography>
63 </Box>
64 </Grid>
65
66 <Grid item xs={12} md={6}>
67 <Box>
68 <img
69 src={Sports}
70 alt="Sports"
71 />
72 <Typography variant="h5">
73 {Content}
74 </Typography>
75 <Typography variant="body1">
76 {Content}
77 </Typography>
78 </Box>
79 </Grid>
80 </Grid>
81 </Container>
82 </Box>
83 );
84};
85
86export default Home;- The Home component is the main page. It displays a welcome message, a brief description of the website, and the latest news in sections like world news, entertainment, sports, and technology.
- Other pages have a similar structure.
Output:






Conclusion:
To wrap it up, this app provides a well-organized and simple layout for a news website. It allows easy navigation between pages using react-router-dom. Each section—like Home, World, Entertainment, Sports, and Technology—has its own content space. Thanks to React Router, the app behaves like a single-page app, meaning no full-page reloads are needed. This makes the browsing experience smoother, and it's easy to add or update sections when needed. Overall, it shows how React can create scalable and easy-to-navigate web applications.