3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[antd] TableのColumnやColumnGroupは(現在)ただの印である

Last updated at Posted at 2022-01-27

この記事は2022年1月現在なので、将来変わるかもしれません

TableのColumnColumnGroup

Ant DesignのTableを使う際に、ColumnColumnGroupを使いますが、

Table - Ant Design

Since this is just a syntax sugar for the prop columns, you can't compose Column and ColumnGroup with other Components.

jsxで記述する ColumnColumnGroupはわかりやすさのために中身がない糖衣構文的なコンポーネントである。

つまり、ただの印であり実装上の意味を持ちません。

(そもそも昔はjsxで記述するものではなくオブジェクトで記述するものだったため?)

実装
https://github.com/ant-design/ant-design/blob/master/components/table/Column.tsx

例えば公式サンプルのこの例

https://codesandbox.io/s/yqy7e

image.png

ですが、

すべて div タグに書き換えても同じように動きます。

image.png

理由

Ant Designというより、さらに依存している react-component/table の仕様にはなるのですが、

https://github.com/react-component/table/blob/master/src/hooks/useColumns.tsx#L22

ここの部分で key と props だけ取り出していることがわかります。

コンポーネント名を活かすならtypeなども活用されるはずです。

つまり、jsxのpropsやchildren(子要素)があるかどうかだけに影響されるのです。

できないこと

別にそういうこともあるよねくらいの気持ちでも良いのですが、

これでできないことは列に対するカスタムコンポーネントが作れなくなります。

実用上だと列を動的に生成したいなどでこのようにすることもあると思います。

export const CustomColomn = () => {
  return <Column title="Age" dataIndex="age" key="age" />
}

のように作ってjsxで使っても、 何も表示されなくなります。

image.png

忘れやすいですがカスタムコンポーネントは、処理の分離だけできるというわけでなく

実装上は もちろん CustomColomn というコンポーネントを1段階挟んでいて propsなどは空になっているのです。

ちなみに、

<Table dataSource={data}>
    {CustomColomn()}
</Table>,

のように関数呼び出しにすれば大丈夫ではありますが、これが良いかどうかは..皆さんのご判断で

image.png

propsも設定すると大丈夫にはなりますが、
カスタムコンポーネントを使って分離する意義が少し薄れます。

<Table dataSource={data}>
    <CustomColumn title="Age" dataIndex="age" key="age"  />
</Table>,

image.png

mapを使って動的に列の数も増やすという場合

こういうコンポーネントを使っても何も出ないということになります。

export const CustomColomns = () => {
  return [1, 2, 3].map((v) => <Column title={"param" + v} />);
};

image.png

なので動的に列を増やしたいときは Table直下にコンポーネントを経由せずにmapを書かないといけないと思います。

<Table dataSource={data}>
    {[1, 2, 3].map((v) => (
      <Column title={"param" + v} />
    ))}
</Table>,

image.png

まとめ

ColumnColumnGroupは、実装上は意味を持たないものである。
ですが、将来仕様が変わるかもしれないのでもちろんこれらを使うべきである。

処理の分離するときにカスタムコンポーネントをよく使うが、1段挟まれるので、
等価ではなく意図しない挙動になるかもしれないという考慮には入れておく。
(おそらく大抵は大丈夫だと思うが)
このコンポーネント以外にもこういうのはあるかもしれないです。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?