Author avatar

Kamran Ayub

Composing React Components with TypeScript

Kamran Ayub

  • Jan 17, 2019
  • 18 Min read
  • 20,464 Views
  • Jan 17, 2019
  • 18 Min read
  • 20,464 Views
React
TypeScript

Introduction

In this guide, you will learn how to compose React.js components using the compile-to-JavaScript language, TypeScript. Using TypeScript with React allows you to develop strongly-typed components that have identifiable props and state objects, which will ensure any usages of your components are type checked by the compiler.

Composing components with React and TypeScript presents some nuances that may not be intuitive at first glance and this guide will cover the most common scenarios.

The guide assumes you are already familiar with React and TypeScript as separate technologies and how to statically type React components with TypeScript.

Referencing React Typings

To access React TypeScript typings, ensure your TypeScript-based React project has the @types/react installed:

1
npm install @types/react --dev
bash

The React typings package will allow you to import types from the react module that TypeScript will understand.

Start by importing React in your TypeScript file:

1
import * as React from "react";
typescript

The official Facebook create-react-app package supports TypeScript out-of-the-box.

Composing a Game of Checkers

This guide uses the game of checkers (or draughts) as an example to showcase composing components that would likely be used to build a React-based checkers game.

Checkers is composed of game pieces moved around on a 10x10 grid of squares and moved according to specific rules

Composition Over Inheritance

Games are traditionally thought of as more object-oriented in nature. In the game of checkers, the circular game pieces ("pawns") can only move forward. Once they reach the "king's row" they can be crowned "king" and gain additional advantages like moving backward but they still inherit the same behavior as pawns.

When modeling React components for these two "types" of game pieces, there might be a temptation to model it the same way using inheritance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
interface PieceProps {
    color: "red" | "black";
}

const Piece = (props: PieceProps) => (
    <svg />
)

class Pawn extends React.Component<PawnProps> {
  render() {
    return <Piece color={this.props.color} />;
  }

  /* pawn behaviors */
}

class King extends Pawn {
  render() {
    return (
      <React.Fragment>
        <Piece color={this.props.color} />
        <Piece color={this.props.color} />
      </React.Fragment>
    );
  }

  /* specific King behaviors */
}
typescript

The King component needs to display a stack of two checker pieces and so it overrides the render method of the Pawn component. This inheritance pattern will allow the King component to reuse behaviors from its Pawn base class.

In React this is discouraged and instead it's recommended to favor composing React components together. By using inheritance, it forces all variations of a component to be class-based components instead of allowing for stateless functional components.

With the addition of TypeScript, the mechanics of inheritance with component props and state become even more problematic. For example, what if King required different props than Pawn? To strongly-type this using props, Pawn would need to become a generic class component:

1
2
3
class Pawn<TProps = PawnProps> extends React.Component<TProps> {}

class King extends Pawn<KingProps> {}
typescript

For illustrative purposes it doesn't matter what the props are, just that it becomes cumbersome to statically type and customize the rendering of inherited components. Even in the example above, I am using a default generic parameter (TProps = PawnProps) to set the default props type of Pawn to PawnProps, otherwise you'd be forced to always specify the props type when you consume the component:

1
<Pawn<PawnProps> color="red" />
typescript

Instead, let's walk through several patterns of how to compose React components together that achieves the same objective as inheritance but in a more controlled, flexible, and safe way.

Composition with Specialization

Instead of having King inherit from Pawn, let's think about it differently. King is a special kind of Pawn that is a stack of two checker pieces.

We can use a <Stack /> component to encapsulate the rendering of multiple checker pieces and both game pieces can customize their own Stack component:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
interface PieceProps {
  color: "red" | "black";
}

interface StackProps {
  size: number;
  pieceProps: PieceProps;
}

const Stack = ({ size, pieceProps }: StackProps) => (
  <React.Fragment>
    {new Array(size).map((_, index) => (
      <Piece key={index.toString()} {...pieceProps} />
    ))}
  </React.Fragment>
);

const Pawn = (props: PieceProps) => <Stack size={1} pieceProps={props} />;

const King = (props: PieceProps) => <Stack size={2} pieceProps={props} />;
typescript

Now King and Pawn are specialized components that configure the Stack component props in a specific way. The pieceProps prop is provided to allow you to pass props down to the <Piece /> component.

In TypeScript, we've defined two interfaces representing our prop types and share the same PieceProps between both the Pawn and King component.

The <Stack /> component accepts a pieceProps prop that is then spread down onto the <Piece /> component. This is sometimes called "props spreading" or "props passing" and gives the consumer more control over the behavior without knowing anything about how Stack works.

Containers and Children

To place the checker pieces on a board, most likely there is a Board component that contains a grid of squares.

Since a Square can contain any kind of checker piece, we can take advantage of React's children prop which represents a way to pass-through child React elements.

Remember that, even though it's most common to use JSX with React, you can write React components in plain JS using React.createElement whose third argument is ...children which enables nesting of components:

1
2
3
React.createElement("div", null, 
  React.createElement("p", null, "Some text"),
  React.createElement("p", null, "Another paragraph"));
js

And the equivalent in JSX:

1
2
3
4
<div>
  <p>Some text</p>
  <p>Another paragraph</p>
</div>
ts

The <p /> elements are the children of the <div /> element. In React, any child elements can be accessed from the parent component's props as children:

1
2
3
4
5
6
interface SquareProps {
  color: "red" | "black";
}
const Square: React.FunctionComponent<SquareProps> = props => (
  <div style={{ backgroundColor: props.color }}>{props.children}</div>
);
ts

Using the React.FunctionComponent type annotation, we can have strongly-typed access to the children prop. The grid cell will simply render whatever children are passed to it. This type of pattern is typically called a Container pattern.

Now the <Board /> component can manipulate what Square a game piece is in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const BOARD_SIZE = 10;

interface OwnState {
  pieces: { [key: number]: React.ReactNode | null };
}

class Board extends React.Component<{}, OwnState> {
  public state = { pieces: this.initializePieces() };

  public render() {
    const squares = [...Array(BOARD_SIZE).keys()];

    return (
      <div>
        {squares.map(row => (
          <div>
            {squares.map(col => (
              <Square key={`${col},${row}`} color={(row * BOARD_SIZE + col) % 2 ? "red" : "black"}>
                {this.state.pieces[row * BOARD_SIZE + col]}
              </Square>
            ))}
          </div>
        ))}
      </div>
    );
  }

  private initializePieces() {
    // create initial board configuration
    // and place pieces in respective spots
  }
}
typescript

This example scaffolds out what a checkers board implementation in React might look like. A 10x10 grid is used to define the game board.

The render method creates the grid of Square components and places a piece within the Square if it exists in the game state. It also decides what color the square background should be based on an even/odd calculation.

Our game grid is represented as a 1D array. The equation y * MAX_WIDTH + x is an efficient way to access a specific (x, y) 2D coordinate when using one dimension.

Composing Using Render Props

The Square component is an example of a simple container. However, you aren't limited to just passing through children components. The children (or any other prop) can also be a function that takes new props and returns React elements. This way, the container can influence the behavior of its children dynamically without knowing what its children are. This is known as a render prop component.

For example, currently, we are setting the <Square /> color prop inline within the render method.

Recall earlier that the React.FunctionComponent type annotation allowed us to access the children prop in a strongly-typed fashion. If we take a peek at the type definitions, we can see the children prop is typed like:

1
children?: React.ReactNode
typescript

The problem with this is that we now want to pass a function as the children prop. This is allowed in vanilla JavaScript React but TypeScript will throw an error if we try to do that using the render prop pattern. We must augment the type definitions to change what the children prop is typed as:

1
2
3
4
5
6
7
8
9
interface SquareBackgroundProps {
  x: number;
  y: number;
  children: (props: SquareBackgroundChildrenProps): React.ReactElement<any>;
}

interface SquareBackgroundChildrenProps {
  backgroundColor: "red" | "black";
}
typescript

Here we are declaring an explicit children prop that is a function that takes new props (SquareBackgroundChildrenProps) and returns a React element. TypeScript will merge this interface declaration with the React typings so that SquareBackgroundProps.children overrides the default prop type.

Why React.Element<T> vs. React.ReactNode? The React.FunctionComponent<T> definition has a return type of React.ReactElement<T>, so we must match that interface otherwise TypeScript will throw a type error. A functional component is more strict than React.ReactNode allows.

We can go a step further and utilize generic types to create a helper interface for any future render prop components:

1
2
3
4
5
6
7
8
9
interface RenderProp<TChildrenProps, TElement = any> {
    (props: TChildrenProps): React.ReactElement<TElement>;
}

interface SquareBackgroundProps {
    x: number;
    y: number;
    children: RenderProp<{ backgroundColor: "red" | "black" }>;
}
typescript

The RenderProp interface is a function interface in TypeScript, denoted using the (...args): T annotation.

Now that the definition is shortened, we can simplify the definition further by removing the need for an extra interface and pass the inline object definition to RenderProp<T> instead. We can also add a generic default for TElement = any to provide optional type checking for the returned React element.

The SquareBackground render prop component will calculate the background color render the children with new props:

1
2
3
4
5
6
7
8
9
const SquareBackground: React.FunctionComponent<
  SquareBackgroundProps
> = props => {
  if ((props.y * BOARD_SIZE + props.x) % 2) {
    return props.children({ backgroundColor: "black" });
  } else {
    return props.children({ backgroundColor: "red" });
  }
};
typescript

Then replace the existing code with our new render prop component:

1
2
3
4
5
6
7
8
9
{squares.map(col =>
+     <SquareBackground key={`${col},${row}`} x={col} y={row}>
+        {({ backgroundColor }) =>
-     <Square key={`${col},${row}`} color={(row * BOARD_SIZE + col) % 2 ? 'red' : 'black'}>
+         <Square color={backgroundColor}>
          {this.state.pieces[row * BOARD_SIZE + col]}
+         </Square>}
+      </SquareBackground>
)}
diff

The SquareBackground component is now encapsulating the logic of determining color, which makes the code easier to read and easier to test. While this example is simple, the render prop pattern is powerful once you need to start representing more sophisticated props or behaviors.

Composing Using Higher-Order Components (HOCs)

A higher-order component is a function that wraps a component with another component and can be used to effectively share common logic in a way that can be composable.

Without TypeScript, for example, this HOC will wrap any component and add logging for the game to debug issues:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function withLogging(WrappedComponent) {
  const logger = {
    info(...args) {
      console.log("[INFO]", ...args);
    }
  };

  return class extends React.Component {
    componentDidMount() {
      logger.info("component mounted", WrappedComponent);
    }

    render() {
      logger.info("component rendered", WrappedComponent);

      return <WrappedComponent {...this.props} />;
    }
  };
}
js

This presents an interesting challenge with TypeScript as we need to effectively allow strongly-typed props passing between these components.

Here's an example of using withLogging that should still provide type checking support:

1
2
3
4
5
6
7
const EnhancedPawn = withLogging(Pawn);
const EnhancedKing = withLogging(King);

const Usage = () => [
    <EnhancedPawn color="red" />,
    <EnhancedKing color="black" />
];
typescript

As you can see, the HOC must preserve the PieceProps interface both the Pawn and King component use so that the TypeScript compiler can provide autocomplete and type support.

To achieve this, we can use generic types with the withLogging function to passthrough the props type detected on the component:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- function withLogging(WrappedComponent) {
+ function withLogging<TProps>(WrappedComponent: React.ComponentType<TProps>) {
  const logger = {
    info(...args) {
      console.log("[INFO]", ...args);
    }
  };
- return class extends React.Component {
+ return class extends React.Component<TProps> {
    componentDidMount() {
      logger.info("component mounted", WrappedComponent);
    }

    render() {
      logger.info("component rendered", WrappedComponent);

      return <WrappedComponent {...this.props} />;
    }
  };
}
diff

TypeScript will now ensure the wrapped component's prop type passes through to the new inline class wrapper component we are returning from the function.

To append additional props that the wrapper component requires, we can use a type intersection:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
+ interface LoggingProps {
+     mountedLogMessage?: string;
+ }

function withLogging<TProps>(WrappedComponent: React.ComponentType<TProps>) {
  const logger = {
    info(...args) {
      console.log("[INFO]", ...args);
    }
  };
- return class extends React.Component<TProps>
+ return class extends React.Component<TProps & LoggingProps> {
    componentDidMount() {
-      logger.info("component mounted", WrappedComponent);        
+      logger.info(this.props.mountedLogMessage || "component mounted", WrappedComponent);
    }

    render() {
      logger.info("component rendered", WrappedComponent);

      return <WrappedComponent {...this.props} />;
    }
  };
}
diff

In this case, we wish to add a customizable message when the wrapped component mounts. By using the type intersection TProps & LoggingProps we ensure that our custom logging props intersect with the original TProps.

This is the final merged props type that TypeScript will "see" at compile-time:

1
2
3
4
{
    color: 'red' | 'black';
    mountedLogMessage?: string;
}
typescript

We can update our usage accordingly and the TypeScript compiler will understand our intent:

1
2
3
4
5
6
7
8
9
const EnhancedPawn = withLogging(Pawn);
const EnhancedKing = withLogging(King);

const Usage = () => [
-    <EnhancedPawn color="red" />,
-    <EnhancedKing color="black" />
+    <EnhancedPawn color="red" mountedLogMessage="Pawn mounted" />,
+    <EnhancedKing color="black" mountedLogMessage="King mounted" />
]
diff

Higher-order components are a powerful pattern but it does require some work to ensure the TypeScript compiler understands how to strongly-typed the wrapper and wrapped components.

Note: Most issues with HOCs and TypeScript are due to improper or mismatching type annotations. Remember that in React, a consumer and the component itself may expect different props to be available since HOCs add props on top of what a component expects by itself. The type intersection operator (&) makes this possible.

Conclusion

This guide walked through several common patterns in React to compose components together to reuse code. Using TypeScript ensures that these patterns continue to provide the benefits of strong type checking and discoverability developers have come to enjoy without resorting to the any catch-all type.

Reference Code Sample

The full working sample which you can modify or view on your own can be found here on CodeSandbox: https://codesandbox.io/s/m559vox21p

19