React Router Typescript

React Router is a popular routing library for React applications, and it can be easily integrated with TypeScript to provide type safety and better documentation of your routes.

Many times you want to pass an ID or other value with the URL, and you can define that part of the URL as a dynamic placeholder:

import { BrowserRouter, Routes, Route } from 'react-router-dom';

const App: React.FC = () => (
	<BrowserRouter>
		<Routes>
			<Route path="/" element={<Home />} />
			<Route path="users/:id" element={<Users />} />
		</Routes>
	</BrowserRouter>
);

With these setup, navigating to different pages is done by using the Link component from react-router-dom. For example, if you want to navigate to the users page with a specific ID, you would do this:

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

const HomePage: React.FC = () => (
	<div>
		<h1>Home Page</h1>
		<Link to="/users/42">Go to User 42 Page</Link>
	</div>
);

export default HomePage;

To strongly type the props that you send to a page through the URL, you can use the useParams hook from react-router-dom.

For example, if you want to pass an id prop to the UserPage, you can do the following:

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

interface Params {
	id: string;
}

const UserPage: React.FC = () => {
	const { id } = useParams<Params>();

	return (
		<div>
			<h1>User Page</h1>
			<p>ID: {id}</p>
		</div>
	);
};

export default UserPage;

In this example, the useParams hook is used to extract the id from the URL and assign it to the id constant.

The generic type <Params> is used to strongly type the id parameter and ensure that it’s of type string.

Another way to strongly type your React Router props is by extending the RouteComponentProps:

import React from 'react';
import { RouteComponentProps } from 'react-router';

interface UserPageProps
	extends RouteComponentProps<{
		id: string;
	}> {}

const UserPage: React.FC<UserPageProps> = ({ match }, props) => {
	const { id } = match.params;

	return (
		<div>
			<h1>User Page</h1>
			<p>ID: {id}</p>
		</div>
	);
};

export default UserPage;


In this example, we extend the RouteComponentProps interface to define the expected parameters in the URL.

Then, in the component, we use destructuring to extract the id parameter from the params property of the match prop.

No comments:

Post a Comment