5
3

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.

material-tableで先頭行を固定する方法

Posted at

テーブルの先頭行を固定したい。
たったこれだけのことでハマってしまったので備忘として残します。

まず material-table とは

この説明を省くと誤解される可能性があるので。
これです↓
https://material-table.com/#/

material-uiをベースに作られた簡単にデータテーブルを実装できるOSSです。
簡単にフィルター、検索、ソートなどの機能をつけられるので、
material-uiのDataGridで頑張る必要がありません。

先頭行を固定する方法

material-tableを編集したい場合は
<MaterialTable />内にプロパティを設定することで簡単に編集できます。

プロパティ一覧↓
https://material-table.com/#/docs/all-props

先頭行を固定したい場合はheaderStyleを編集すればいいので

table.js
const DataTable = () => {
    return (
      <MaterialTable
        title="DataTable"
        columns={[
            //省略
        ]}
        data={[
            //省略
        ]}        
        options={{
            headerStyle: {position: 'sticky', top: 0},
        }}
      />
    )
}

このようにプロパティにoptionsheaderStyleと書いて
position: 'sticky', top: 0とするだけ。

...と思っていたのですが、これだけでは効きませんでした。

効かなかった理由

material-tableを使うとtableより上の階層にいくつかdivが作られるのですが、
そのうちの2つでoverflowが初期値ではなく別の値に書き換えられていたことが原因でした。

position: stickyは祖先要素にvisible以外のoverflow属性が指定してあると期待通りに動作しない場合があります。

解決方法

原始的な方法ですが、対象のスタイルを上書きして解決しました。

App.css
.Component-horizontalScrollContainer-19,
.Component-horizontalScrollContainer-19 div {
  overflow: visible !important;
}

最後に

もっと綺麗な解決方法がないかなーとドキュメントを眺めていたらこんな一文が。
https://material-table.com/#/docs/features/component-overriding

Container that everything renders in

これを見る限りContainerコンポーネントのオーバーライドで解決できそうな気がしますが、ちょっと難しそうなので触れていません。笑

もし詳しい方がいましたら教えてください!

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?