検索
ホームページウェブフロントエンドjsチュートリアルReact と Typescript を使用してカスタム テーブル コンポーネントを作成する方法 (パート 2)

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;
}
</t>

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",
  },
];
</country>

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;
}
</t></t></t>

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>;
};
</country>

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}"></customrow>}
  </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}"></customtable>;

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;
}
</t></t></t>

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}"></customrow>}
</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 サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
JavaScriptの文字列文字を交換しますJavaScriptの文字列文字を交換しますMar 11, 2025 am 12:07 AM

JavaScript文字列置換法とFAQの詳細な説明 この記事では、javaScriptの文字列文字を置き換える2つの方法について説明します:内部JavaScriptコードとWebページの内部HTML。 JavaScriptコード内の文字列を交換します 最も直接的な方法は、置換()メソッドを使用することです。 str = str.replace( "find"、 "置換"); この方法は、最初の一致のみを置き換えます。すべての一致を置き換えるには、正規表現を使用して、グローバルフラグGを追加します。 str = str.replace(/fi

jQuery日付が有効かどうかを確認しますjQuery日付が有効かどうかを確認しますMar 01, 2025 am 08:51 AM

単純なJavaScript関数は、日付が有効かどうかを確認するために使用されます。 関数isvaliddate(s){ var bits = s.split( '/'); var d = new Date(bits [2] '/' bits [1] '/'ビット[0]); return !!(d &&(d.getmonth()1)== bits [1] && d.getdate()== number(bits [0])); } //テスト var

jQueryは要素のパディング/マージンを取得しますjQueryは要素のパディング/マージンを取得しますMar 01, 2025 am 08:53 AM

この記事では、jQueryを使用して、DOM要素の内側のマージン値とマージン値、特に外側の縁と要素の内側の縁の特定の位置を取得して設定する方法について説明します。 CSSを使用して要素の内側と外側の縁を設定することは可能ですが、正確な値を取得するのは難しい場合があります。 // 設定 $( "div.header")。css( "margin"、 "10px"); $( "div.header")。css( "padding"、 "10px"); このコードはそうだと思うかもしれません

10 jQuery Accordionsタブ10 jQuery AccordionsタブMar 01, 2025 am 01:34 AM

この記事では、10個の例外的なjQueryタブとアコーディオンについて説明します。 タブとアコーディオンの重要な違いは、コンテンツパネルの表示方法と非表示にあります。これらの10の例を掘り下げましょう。 関連記事:10 jQueryタブプラグイン

10 jqueryプラグインをチェックする価値があります10 jqueryプラグインをチェックする価値がありますMar 01, 2025 am 01:29 AM

ウェブサイトのダイナミズムと視覚的な魅力を高めるために、10の例外的なjQueryプラグインを発見してください!このキュレーションされたコレクションは、画像アニメーションからインタラクティブなギャラリーまで、多様な機能を提供します。これらの強力なツールを探りましょう。 関連投稿: 1

ノードとHTTPコンソールを使用したHTTPデバッグノードとHTTPコンソールを使用したHTTPデバッグMar 01, 2025 am 01:37 AM

HTTP-Consoleは、HTTPコマンドを実行するためのコマンドラインインターフェイスを提供するノードモジュールです。 Webサーバー、Web Servに対して作成されているかどうかに関係なく、HTTPリクエストで何が起こっているかをデバッグして正確に確認するのに最適です

カスタムGoogle検索APIセットアップチュートリアルカスタムGoogle検索APIセットアップチュートリアルMar 04, 2025 am 01:06 AM

このチュートリアルでは、カスタムGoogle検索APIをブログまたはWebサイトに統合する方法を示し、標準のWordPressテーマ検索関数よりも洗練された検索エクスペリエンスを提供します。 驚くほど簡単です!検索をyに制限することができます

jQueryはscrollbarをdivに追加しますjQueryはscrollbarをdivに追加しますMar 01, 2025 am 01:30 AM

次のjQueryコードスニペットを使用して、Divコンテンツがコンテナ要素領域を超えたときにスクロールバーを追加できます。 (デモンストレーションはありません、それを直接firebugにコピーしてください) // d =ドキュメント // w =ウィンドウ // $ = jQuery var contentarea = $(this)、 wintop = contentarea.scrolltop()、 docheight = $(d).height()、 winheight = $(w).height()、 divheight = $( '#c

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、