JavaScript and React course ยท Module 12: React and TypeScript

Generic Components - Universal Navigation Systems

6 min read ยท
In this lesson5

You have a planet list component. A week later you need a list of stars, then crew members, then ships. You copy the component a fourth time and change only the type - and from now on every bug has to be fixed in four places. Instead, imagine a universal navigation system on a spaceship that can display data about planets, stars, ships - anything you give it. In TypeScript, we create such "universal" components using generics.

What are Generics?

Generics are type parameters - they let you create components and functions that work with different data types while keeping full type control. You write a type parameter in angle brackets, usually a single capital letter T (for "type"). It's a slot for a type that is only supplied at the point of use - like a variable, but for types.

The example uses the Planet and Star interfaces from the props lesson, and planets and stars are arrays of such objects:

// Without generics - you need separate functions
function getFirstPlanet(items: Planet[]): Planet {
  return items[0];
}
function getFirstStar(items: Star[]): Star {
  return items[0];
}

Both functions do exactly the same thing and differ only by type. A generic turns them into one:

// With generics - one function for all types
function getFirst<T>(items: T[]): T {
  return items[0];
}

const planet = getFirst<Planet>(planets);  // returns Planet
const star = getFirst<Star>(stars);        // returns Star
const name = getFirst<string>(["a", "b"]); // returns string

Read getFirst<T>(items: T[]): T as: "for any type T, take an array of T and return one T". The type isn't lost along the way - planet has the type Planet, so the editor suggests its fields. In practice you can skip the brackets at the call site, because TypeScript infers T from the argument: getFirst(planets) gives the same result.

Generic List Component

One of the most common uses of generics in React is a universal list component. The list needs one guarantee: every element must have an id, because React requires a unique key. We write that guarantee with extends - T extends HasId means "T can be anything, as long as it has an id field". This is called a constraint.

// Each element must have an id to use as the key
interface HasId {
  id: number | string;
}

interface ListProps<T extends HasId> {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
  emptyMessage?: string;
}

The renderItem prop is a so-called render prop: a function the parent passes to decide how to draw a single element. The list itself knows nothing about planets - it only knows how to lay them out:

function List<T extends HasId>({ items, renderItem, emptyMessage = "No data" }: ListProps<T>) {
  if (items.length === 0) {
    return <p>{emptyMessage}</p>;
  }

  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{renderItem(item)}</li>
      ))}
    </ul>
  );
}

Thanks to the constraint, item.id is allowed in key. If you tried to read item.name, TypeScript would object - the list has no guarantee such a field exists. A technical note: in a .tsx file an arrow function with a generic needs <T,> with a comma, so the compiler doesn't confuse it with a JSX tag. A function declaration doesn't have this problem.

Using a Generic Component

Let's prepare two different kinds of data. Planets have a numeric id, crew members a string one, and both satisfy HasId:

interface Planet {
  id: number;
  name: string;
  type: string;
}

interface CrewMember {
  id: string;
  name: string;
  rank: string;
}

Now the same List component displays both collections. <List<Planet> passes the type explicitly, although TypeScript would infer it from items:

function Dashboard() {
  const planets: Planet[] = [
    { id: 1, name: "Mars", type: "rocky" },
    { id: 2, name: "Jupiter", type: "gas giant" }
  ];

  const crew: CrewMember[] = [
    { id: "c1", name: "Nova", rank: "Captain" },
    { id: "c2", name: "Ra", rank: "Navigator" }
  ];

  return (
    <div>
      <h2>Planets</h2>
      <List<Planet>
        items={planets}
        renderItem={(planet) => <span>{planet.name} ({planet.type})</span>}
      />

      <h2>Crew</h2>
      <List<CrewMember>
        items={crew}
        renderItem={(member) => <span>{member.name} - {member.rank}</span>}
      />
    </div>
  );
}

In renderItem the planet parameter has the type Planet and member the type CrewMember, with no annotations. The List component didn't change by a single line.

Generic Select Component

The same pattern works for a select field. The constraint requires value and label fields, and onChange hands the parent the whole selected object, keeping its exact type. The change handler uses ChangeEvent from the previous lesson:

interface SelectOption {
  value: string;
  label: string;
}

interface SelectProps<T extends SelectOption> {
  options: T[];
  value: string;
  onChange: (option: T) => void;
  placeholder?: string;
}

function Select<T extends SelectOption>({
  options, value, onChange, placeholder
}: SelectProps<T>) {
  const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const selected = options.find(opt => opt.value === e.target.value);
    if (selected) onChange(selected);
  };

  return (
    <select value={value} onChange={handleChange}>
      {placeholder && <option value="">{placeholder}</option>}
      {options.map(opt => (
        <option key={opt.value} value={opt.value}>
          {opt.label}
        </option>
      ))}
    </select>
  );
}

The find method can return undefined, so if (selected) is required - TypeScript won't let you pass a possible undefined to onChange.

Generic Constraints

The extends keyword lets you restrict which types are accepted. The constraint can be an inline type or a named interface:

// T must have a 'name' field
function displayName<T extends { name: string }>(item: T): string {
  return item.name;
}

// T must implement the Sortable interface
interface Sortable {
  sortOrder: number;
}

function sortItems<T extends Sortable>(items: T[]): T[] {
  return [...items].sort((a, b) => a.sortOrder - b.sortOrder);
}

A constraint is a minimum, not an exact shape: the object may have extra fields and they are kept in the result type. [...items] creates a copy, so sorting doesn't modify the original array. My advice: reach for a generic only when the same component really handles two different data types - before that, a plain interface is enough. In the final project you'll build a generic data table.

Code for this lesson: App.tsx
import React, { useState } from 'react';

// Generic constraint - every element must have an id
interface HasId {
  id: number | string;
}

// Generic list component
interface ListProps<T extends HasId> {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
  title: string;
  emptyMessage?: string;
}

function List<T extends HasId>({ items, renderItem, title, emptyMessage = "No items" }: ListProps<T>) {
  return (
    <div className="list-container">
      <h2>{title} ({items.length})</h2>
      {items.length === 0 ? (
        <p className="empty">{emptyMessage}</p>
      ) : (
        <ul className="list">
          {items.map(item => (
            <li key={item.id} className="list-item">{renderItem(item)}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

// Different data types
interface Planet {
  id: number;
  name: string;
  type: string;
  habitable: boolean;
}

interface CrewMember {
  id: string;
  name: string;
  rank: string;
  specialization: string;
}

interface Mission {
  id: number;
  codeName: string;
  status: "planned" | "active" | "completed";
  destination: string;
}

function App() {
  const [planets] = useState<Planet[]>([
    { id: 1, name: "Kepler-442b", type: "rocky", habitable: true },
    { id: 2, name: "HD 209458 b", type: "gaseous", habitable: false },
    { id: 3, name: "Proxima Centauri b", type: "rocky", habitable: true },
  ]);

  const [crew] = useState<CrewMember[]>([
    { id: "c1", name: "Nova", rank: "Captain", specialization: "Navigation" },
    { id: "c2", name: "Ra", rank: "Navigator", specialization: "Astrophysics" },
    { id: "c3", name: "Astro", rank: "Engineer", specialization: "Engines" },
  ]);

  const [missions] = useState<Mission[]>([
    { id: 1, codeName: "DAWN", status: "active", destination: "Mars" },
    { id: 2, codeName: "HORIZON", status: "planned", destination: "Jupiter" },
  ]);

  const statusColors = { planned: "#f59e0b", active: "#22c55e", completed: "#6b7280" };

  return (
    <div className="app">
      <h1>Generic Components</h1>

      <List<Planet>
        title="Planets"
        items={planets}
        renderItem={(planet) => (
          <div className="item-content">
            <strong>{planet.name}</strong>
            <span className="detail">{planet.type}</span>
            <span className={"badge " + (planet.habitable ? "green" : "red")}>
              {planet.habitable ? "Habitable" : "Uninhabitable"}
            </span>
          </div>
        )}
      />

      <List<CrewMember>
        title="Crew"
        items={crew}
        renderItem={(member) => (
          <div className="item-content">
            <strong>{member.name}</strong>
            <span className="detail">{member.rank}</span>
            <span className="spec">{member.specialization}</span>
          </div>
        )}
      />

      <List<Mission>
        title="Missions"
        items={missions}
        renderItem={(mission) => (
          <div className="item-content">
            <strong>{mission.codeName}</strong>
            <span className="detail">{mission.destination}</span>
            <span style={{ color: statusColors[mission.status] }}>
              {mission.status.toUpperCase()}
            </span>
          </div>
        )}
      />
    </div>
  );
}

export default App;

Remember: a generic is a universal docking port - every ship that meets the port's requirements docks without rebuilding the station.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the <T> notation mean in the declaration function getFirst<T>(items: T[]): T?

  2. 2. What does the notation <T extends { id: number }> mean in a generic React component?

Hands-on tasks in the game

  • Vertical ordering

    Arrange the steps for creating a generic list component in the correct order:

  • Code editor

    Generic Select component with constraints

  • Horizontal ordering

    Arrange the syntax of a generic constraint in TypeScript:

  • Code editor

    Generic component with render prop and filtering

  1. QuestionGenerics in TypeScript
  2. Put in orderCreating a Generic Component
  3. Coding taskPractice: Generic Select Component
  4. QuestionGeneric Constraint
  5. Put in orderGeneric Constraint Syntax
  6. Coding taskPractice: Generic List with Filtering

Useful articles