traintocode

React Router

TypeScript enhances React Router by providing strong typing for route parameters, history, and navigation. This gives you type safety when navigating between routes and handling URL parameters in your React application.

Firstly, define the types for your route parameters. For instance, if you have a route with a parameter userId, you can create a type:

type UserRouteParams = {
  userId: string;
}

Now, use this type with RouteComponentProps from react-router-dom to type your component props:

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

const UserPage: React.FC<RouteComponentProps<UserRouteParams>> //...

This ensures that userId is always treated as a string within your component, preventing type-related bugs.

Exercise
Refactor the existing UserProfile component to use TypeScript with RouteComponentProps. Ensure that the userId parameter from the URL is correctly typed and used within the component.
    You cannot do the coding exercises on this device, visit this page on a larger screen.
    App.tsx
    Loading...