React と Typescript を使用してカスタム テーブル コンポーネントを作成する方法 (パート 2)

Patricia Arquette
リリース: 2024-10-09 18:25:02
オリジナル
468 人が閲覧しました

Introduction

Yay! ? You've made it to the final part of this two-part series! If you haven't already checked out Part 1, stop right here and go through that first. Don't worry, we'll wait until you’re back! ?

In Part 1, we built the CustomTable component. You can see it in action here.

In this second part, we’ll be extending the component to add some new features. Here's what we'll be working towards:
How to create a custom table component with React and Typescript (Part 2)

To support this, the CustomTable component will need some enhancements:

  1. The ability to format the rendered value—e.g., rendering a number with proper formatting.
  2. Flexibility to allow users to provide custom templates for rendering rows, giving them control over how each column is displayed.

Let's dive into building the first feature.

Extending the Column Interface

We’ll start by adding a format method to the Column interface to control how specific columns render their values.

interface Column<T> {
  id: keyof T;
  label: string;
  format?: (value: string | number) => string;
}
ログイン後にコピー

This optional format method will be used to format data when necessary. Let’s see how this works with an example from the Country.tsx file. We’ll add a format method to the population column.

const columns: Column<Country>[] = [
  { id: "name", label: "Name" },
  { id: "code", label: "ISO\u00a0Code" },
  {
    id: "population",
    label: "Population",
    format: (value) => new Intl.NumberFormat("en-US").format(value as number),
  },
  {
    id: "size",
    label: "Size\u00a0(km\u00b2)",
  },
  {
    id: "density",
    label: "Density",
  },
];
ログイン後にコピー

Here, we’re using the JavaScript Intl.NumberFormat method to format the population as a number. You can learn more about this method here.

Next, we need to update our CustomTable component to check for the format function and apply it when it exists.

<TableBody>
  {rows.map((row, index) => (
    <TableRow hover tabIndex={-1} key={index}>
      {columns.map((column, index) => (
        <TableCell key={index}>
          {column.format
            ? column.format(row[column.id] as string)
            : (row[column.id] as string)}
        </TableCell>
      ))}
    </TableRow>
  ))}
</TableBody>
ログイン後にコピー

With this modification, the population column now renders with the appropriate formatting. You can see it in action here.

Supporting Custom Templates

Now, let's implement the next feature: allowing custom templates for rendering columns. To do this, we’ll add support for passing JSX as a children prop or using render props, giving consumers full control over how each cell is rendered.

First, we’ll extend the Props interface to include an optional children prop.

interface Props<T> {
  rows: T[];
  columns: Column<T>[];
  children?: (row: T, column: Column<T>) => React.ReactNode;
}
ログイン後にコピー

Next, we’ll modify our CustomTable component to support this new prop while preserving the existing behavior.

<TableRow>
  {columns.map((column, index) => (
    <TableCell key={index}>
      {children
        ? children(row, column)
        : column.format
        ? column.format(row[column.id] as string)
        : row[column.id]}
    </TableCell>
  ))}
</TableRow>
ログイン後にコピー

This ensures that if the children prop is passed, the custom template is used; otherwise, we fall back to the default behavior.

Let’s also refactor the code to make it more reusable:

const getFormattedValue = (column, row) => {
  const value = row[column.id];
  return column.format ? column.format(value) : value as string;
};

const getRowTemplate = (row, column, children) => {
  return children ? children(row, column) : getFormattedValue(column, row);
};
ログイン後にコピー

Custom Row Component

Now let’s build a custom row component in the Countries.tsx file. We’ll create a CustomRow component to handle special rendering logic.

interface RowProps {
  row: Country;
  column: Column<Country>;
}

const CustomRow = ({ row, column }: RowProps) => {
  const value = row[column.id];
  if (column.format) {
    return <span>{column.format(value as string)}</span>;
  }
  return <span>{value}</span>;
};
ログイン後にコピー

Then, we’ll update Countries.tsx to pass this CustomRow component to CustomTable.

const Countries = () => (
  <CustomTable columns={columns} rows={rows}>
    {(row, column) => <CustomRow column={column} row={row} />}
  </CustomTable>
);
ログイン後にコピー

For People.tsx, which doesn’t need any special templates, we can simply render the table without the children prop.

const People = () => <CustomTable columns={columns} rows={rows} />;
ログイン後にコピー

Improvements

One improvement we can make is the use of array indexes as keys, which can cause issues. Instead, let’s enforce the use of a unique rowKey for each row.

We’ll extend the Props interface to require a rowKey.

interface Props<T> {
  rowKey: keyof T;
  rows: T[];
  columns: Column<T>[];
  children?: (row: T, column: Column<T>) => React.JSX.Element | string;
  onRowClick?: (row: T) => void;
}
ログイン後にコピー

Now, each consumer of CustomTable must provide a rowKey to ensure stable rendering.

<CustomTable
  rowKey="code"
  rows={rows}
  onRowClick={handleRowClick}
  columns={columns}
>
  {(row, column) => <CustomRow column={column} row={row} />}
</CustomTable>
ログイン後にコピー

Final Code

Check out the full code here.

Conclusion

In this article, we extended our custom CustomTable component by adding formatting options and the ability to pass custom templates for columns. These features give us greater control over how data is rendered in tables, while also making the component flexible and reusable for different use cases.

We also improved the component by enforcing a rowKey prop to avoid using array indexes as keys, ensuring more efficient and stable rendering.

I hope you found this guide helpful! Feel free to share your thoughts in the comments section.

Thanks for sticking with me through this journey! ?

以上がReact と Typescript を使用してカスタム テーブル コンポーネントを作成する方法 (パート 2)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート