Some reflections about React and TypeScript

rossanodan

Rossano D'Angelo

Posted on January 25, 2020

Some reflections about React and TypeScript

Since I am using TypeScript, I have some superpowers.

I can improve my code adding things like interfaces and return types. This won't change the behavior of the application but will make it easier to debug and more bug free.

Interfaces

I know that a route is an object structured as follows

{
  path: '/teams',
  sidebarName: 'Teams',
  component: Teams
},

The Routes module is used in different places within the application so it makes sense exporting an interface that defines the structure of each route.

In the Routes.ts file

...
export interface IRoute {
  path: string;
  sidebarName: string;
  component: React.ComponentType;
}
...
const Routes: IRoute[] = [
...

At this point is straight forward importing it from elsewhere.
In the App.tsx indeed I do

import Routes, { IRoute } from './Routes';
...
{Routes.map((route: IRoute) => (
  <Route exact path={route.path} key={route.path}>
    <route.component />
  </Route>
))}

Return types

When writing TypeScript is a good practice specifying functions' return types.

For example, a simple functional component like Home returns a JSX.Element

const Home: React.FC = (): JSX.Element => {
  return (
    <h1>Home</h1>
  );
};

A method like activeRoute returns a boolean

const activeRoute = (routeName: string): boolean => {
  return location.pathname === routeName ? true : false;
}

And so on.

Adding return types helps avoiding common misktakes and makes the application more testable.

props type

React Router DOM offers also the type of the props that a wrapped component receives. For example, I have withRouter(NavigationBar) receiveing some props form the HOC withRouter.

const NavigationBar: React.FC = (props: any) => {

The type of those props is RouteComponentProps.

import { NavLink, withRouter, RouteComponentProps } from 'react-router-dom';
...
const NavigationBar: React.FC<RouteComponentProps> = ({ history, location, match }: RouteComponentProps) => {

I also destructured the props to have direct access to its properties history, location and match.

💖 💪 🙅 🚩
rossanodan
Rossano D'Angelo

Posted on January 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related