Overview
React Router is a popular library for handling navigation in React applications. It can be combined with TypeScript to provide a type-safe routing experience, reducing runtime errors. Using React Router with TypeScript, we will demonstrate how type-safe routing can be implemented in React.
If you are new to React TypeScript or still learning about it, I recommend you read my article "How to Get Started with React TypeScript".
Installing Dependencies
We will start by installing the required packages.
npm install react-router-dom @types/react-router-dom
Creating Routes with TypeScript
To encapsulate our routes, we will use the Route component from the React Router. Below is an example of how to create a Routes component.
// App.tsx
import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Navigation from './Components/Navigation';
import RedirectToHome from './Components/RedirectToHome';
import Home from './Screens/Home';
import About from './Screens/About';
import Contact from './Screens/Contact';
import UserProfile from './Screens/UserProfile';
const App: React.FC = () => {
return (
<Router>
<div>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/redirect" element={<RedirectToHome />} />
<Route path="/userprofile/:username" element={<UserProfile />} />
</Routes>
</div>
</Router>
);
};
export default App;
Navigating Between Routes
In order to ensure type safety, we will be using the Link component to create links between routes.
//Simple way to Navigate Between Routes with TypeScript
import React from 'react';
import { Link } from 'react-router-dom';
const Navigation: React.FC = () => {
let username = 'JoeBlog';
return (
(<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/redirect">Redirect To Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
<li>
<Link to={`/userprofile/${username}`}>User Profile</Link>
</li>
</ul>
</nav>)
);
};
export default Navigation;

Join the conversation! Your thoughts help the community grow.